forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain2.cpp
More file actions
40 lines (29 loc) · 790 Bytes
/
main2.cpp
File metadata and controls
40 lines (29 loc) · 790 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
31
32
33
34
35
36
37
38
39
40
/// Source : https://leetcode.com/problems/candy/
/// Author : liuyubobobo
/// Time : 2018-12-10
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
/// Two arrays's thinking
/// But only use one array :-)
///
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> res(n, 1);
for(int i = 1; i < n; i ++)
if(ratings[i] > ratings[i - 1])
res[i] = res[i - 1] + 1;
for(int i = n - 2; i >= 0; i --)
if(ratings[i] > ratings[i + 1] && res[i] <= res[i + 1])
res[i] = res[i + 1] + 1;
return accumulate(res.begin(), res.end(), 0);
}
};
int main() {
return 0;
}