This commit is contained in:
parent
fa934cf225
commit
f4912703f9
14
include/s0135_candy.hpp
Normal file
14
include/s0135_candy.hpp
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
#ifndef S0135_CANDY_HPP
|
||||||
|
#define S0135_CANDY_HPP
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
class S0135 {
|
||||||
|
public:
|
||||||
|
int candy(vector<int>& ratings);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
18
src/s0135_candy.cpp
Normal file
18
src/s0135_candy.cpp
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
#include "s0135_candy.hpp"
|
||||||
|
|
||||||
|
int S0135::candy(vector<int>& ratings) {
|
||||||
|
int len = ratings.size();
|
||||||
|
int result{0};
|
||||||
|
vector<int> 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];
|
||||||
|
}
|
17
tests/s0135_candy.cpp
Normal file
17
tests/s0135_candy.cpp
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
#include "s0135_candy.hpp"
|
||||||
|
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
TEST(Problem135, Case1) {
|
||||||
|
vector<int> ratings{1, 0, 2};
|
||||||
|
int expected{5};
|
||||||
|
S0135 solution;
|
||||||
|
EXPECT_EQ(solution.candy(ratings), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Problem135, Case2) {
|
||||||
|
vector<int> ratings{1, 2, 2};
|
||||||
|
int expected{4};
|
||||||
|
S0135 solution;
|
||||||
|
EXPECT_EQ(solution.candy(ratings), expected);
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user