From f4912703f9606b9c55304f4a8bf012b1bf69ccf3 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 7 Feb 2023 12:36:51 +0800 Subject: [PATCH] s0135 --- include/s0135_candy.hpp | 14 ++++++++++++++ src/s0135_candy.cpp | 18 ++++++++++++++++++ tests/s0135_candy.cpp | 17 +++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 include/s0135_candy.hpp create mode 100644 src/s0135_candy.cpp create mode 100644 tests/s0135_candy.cpp diff --git a/include/s0135_candy.hpp b/include/s0135_candy.hpp new file mode 100644 index 0000000..3ccda45 --- /dev/null +++ b/include/s0135_candy.hpp @@ -0,0 +1,14 @@ +#ifndef S0135_CANDY_HPP +#define S0135_CANDY_HPP + +#include +#include + +using namespace std; + +class S0135 { + public: + int candy(vector& ratings); +}; + +#endif diff --git a/src/s0135_candy.cpp b/src/s0135_candy.cpp new file mode 100644 index 0000000..ded1ce9 --- /dev/null +++ b/src/s0135_candy.cpp @@ -0,0 +1,18 @@ +#include "s0135_candy.hpp" + +int S0135::candy(vector& ratings) { + int len = ratings.size(); + int result{0}; + vector candy(len, 1); + // 从前往后 + for (int i{1}; i < len; ++i) { + if (ratings[i] > ratings[i - 1]) candy[i] = candy[i - 1] + 1; + } + // 从后往前 + for (int i = len - 2; i >= 0; --i) { + if (ratings[i] > ratings[i + 1]) candy[i] = max(candy[i], candy[i + 1] + 1); + // 顺便统计结果 + result += candy[i + 1]; + } + return result + candy[0]; +} diff --git a/tests/s0135_candy.cpp b/tests/s0135_candy.cpp new file mode 100644 index 0000000..4d18734 --- /dev/null +++ b/tests/s0135_candy.cpp @@ -0,0 +1,17 @@ +#include "s0135_candy.hpp" + +#include + +TEST(Problem135, Case1) { + vector ratings{1, 0, 2}; + int expected{5}; + S0135 solution; + EXPECT_EQ(solution.candy(ratings), expected); +} + +TEST(Problem135, Case2) { + vector ratings{1, 2, 2}; + int expected{4}; + S0135 solution; + EXPECT_EQ(solution.candy(ratings), expected); +}