1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: int candy(vector<int>& ratings) { const int n = ratings.size(); int ans = 1, inc = 1, dec = 0, pre = 1; for (int i = 1; i < n; ++i) if (ratings[i] >= ratings[i - 1]) { dec = 0; pre = ratings[i] == ratings[i - 1] ? 1 : pre + 1; ans += pre; inc = pre; } else { ++dec; if (dec == inc) ++dec; ans += dec; pre = 1; } return ans; } };
|