class Solution { public: int candy(vector &ratings) { int n = ratings.size(); int ans = 0; vector sum(n, 1); if (n < 2) return n; for (int i = 0; i < n; ++i) { if (i > 0 && ratings[i] > ratings[i - 1]) sum[i] = sum[i - 1] + 1; } for (int i = n - 1; i >= 0; --i) { if (i < n - 1 && ratings[i] > ratings[i + 1]) sum[i] = max(sum[i + 1] + 1, sum[i]); ans += sum[i]; } return ans; } };