-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23-09-23-Candy.cpp
More file actions
37 lines (31 loc) · 898 Bytes
/
23-09-23-Candy.cpp
File metadata and controls
37 lines (31 loc) · 898 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
/*
Time: O(n)
Space: O(1)
https://leetcode.com/problems/candy/
*/
class Solution {
public:
int candy(vector<int>& ratings) {
if (ratings.size() <= 1) {
return ratings.size();
}
vector<int> candyStore(ratings.size(), 1);
for (int i = 1; i < ratings.size(); i++) { // O(n)
if (ratings[i] > ratings[i - 1]) {
candyStore[i] = candyStore[i - 1] + 1;
}
}
for (int i = ratings.size() - 1; i > 0; i--) { // O(n)
if (ratings[i - 1] > ratings[i]) {
candyStore[i - 1] = max(candyStore[i] + 1, candyStore[i - 1]);
;
}
}
int ans = 0;
for (int i = 0; i < candyStore.size(); i++) { // O(n)
cout << candyStore[i] << endl;
ans += candyStore[i];
}
return ans;
}
};