https://leetcode.com/problems/candy/description/?envType=study-plan-v2&envId=top-interview-150
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> res(n, 1);
res[0] = 1;
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1])
res[i] = res[i - 1] + 1;
}
int ans = res[n - 1];
for (int i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1])
res[i] = max(res[i], res[i + 1] + 1);
ans += res[i];
}
return ans;
}
};
Time Complexity: O(n)
Space: O(n)
從前面掃一次再從後面掃一次,就可以知道結果了。