LeetCode Problem

135. Candy Link to LeetCode There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subjected to the following requirements: Return the minimum number of candies you need to have to distribute the candies to the children. Analysis This problem can be solved in O(n) time. We can always assign a neighbor with 1 more if the neighbor has higher a rating value. However, to get the minimum total number, we should always start adding 1s in the ascending order. We can solve this problem by scanning the array from both sides. First, scan the array from left to right, and assign values for all the ascending pairs. Then scan from right to left and assign values to descending pairs. This problem is similar to Trapping Rain Water. public int candy(int[] ratings) { if (ratings == null || ratings.length == 0) { return 0; } int[] candies = new int[ratings.length]; candies[0] = 1; //from let to right for (int i = 1; i < ratings.length; i++) { if (ratings[i] > ratings[i - 1]) { candies[i] = candies[i - 1] + 1; } else { // if not ascending, assign 1 candies[i] = 1; } } int result = candies[ratings.length - 1]; //from right to left for (int i = ratings.length - 2; i >= 0; i--) { int cur = 1; if (ratings[i] > ratings[i + 1]) { cur = candies[i + 1] + 1; } result += Math.max(cur, candies[i]); candies[i] = cur; } return result; }