-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc_0135.cpp
More file actions
30 lines (29 loc) · 855 Bytes
/
lc_0135.cpp
File metadata and controls
30 lines (29 loc) · 855 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @file lc_0135.cpp
* @brief https://leetcode-cn.com/problems/candy/
* @author YongDu
* @date 2021-10-17
*/
//===------------------------- [Greedy Method] ----------------------------===//
// 1. 从左至右满足左边
// 2. 从右往左满足右边
//===----------------------------------------------------------------------===//
class Solution {
public:
int candy(vector<int> &ratings) {
vector<int> candys(ratings.size(), 1);
// -->
for (int i = 1; i < candys.size(); ++i) {
if (ratings[i] > ratings[i - 1]) {
candys[i] = candys[i - 1] + 1;
}
}
// <--
for (int i = candys.size() - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) {
candys[i] = std::max(candys[i + 1] + 1, candys[i]);
}
}
return std::accumulate(candys.begin(), candys.end(), 0);
}
};