-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcandy.cpp
More file actions
35 lines (35 loc) · 877 Bytes
/
candy.cpp
File metadata and controls
35 lines (35 loc) · 877 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
/* Problem url: https://leetcode.com/problems/candy
* Code by: ldcduc
* */
/* Begin of Solution */
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> left(n);
vector<int> right(n);
for (int i = 0; i < n; ++ i) {
if (i > 0 && ratings[i] > ratings[i - 1]) {
left[i] = left[i - 1] + 1;
} else {
left[i] = 1;
}
}
int result = 0;
for (int i = n - 1; i >= 0; -- i) {
if (i < n - 1 && ratings[i] > ratings[i + 1]) {
right[i] = right[i + 1] + 1;
} else{
right[i] = 1;
}
result += max(left[i], right[i]);
}
return result;
}
};
/* End of Solution */
/*
* Comment by ldcduc
* Suggested tags: array
*
* */