| 3 | #include <algorithm> |
| 4 | |
| 5 | int candies(std::vector<int>& ratings) { |
| 6 | int n = ratings.size(); |
| 7 | // Ensure each child starts with 1 candy. |
| 8 | std::vector<int> candies(n, 1); |
| 9 | // First pass: for each child, ensure the child has more candies |
| 10 | // than their left-side neighbor if the current child's rating is |
| 11 | // higher. |
| 12 | for (int i = 1; i < n; i++) { |
| 13 | if (ratings[i] > ratings[i - 1]) { |
| 14 | candies[i] = candies[i - 1] + 1; |
| 15 | } |
| 16 | } |
| 17 | // Second pass: for each child, ensure the child has more candies |
| 18 | // than their right-side neighbor if the current child's rating is |
| 19 | // higher. |
| 20 | for (int i = n - 2; i >= 0; i--) { |
| 21 | if (ratings[i] > ratings[i + 1]) { |
| 22 | // If the current child already has more candies than their |
| 23 | // right-side neighbor, keep the higher amount. |
| 24 | candies[i] = std::max(candies[i], candies[i + 1] + 1); |
| 25 | } |
| 26 | } |
| 27 | return std::accumulate(candies.begin(), candies.end(), 0); |
| 28 | } |
nothing calls this directly
no outgoing calls
no test coverage detected