Question details
There are n Children standing in a row (numbers from 0 to n-1). Each child has a rating value, which is stored in the ratings array. The teacher needs to allocate candy to them. Each child needs at least one candy. For any two adjacent children, I and I + 1, the value of rating must be smaller than the value of rating. The value of rating must be equal to the value of rating ).
Calculate the minimum number of sweets required to complete the allocation.
Input Format:
Multiple groups of data. The first row of each group is a positive integer n.
In the next n rows, each row has a positive integer, indicating the rating value of each child. All integers cannot exceed 100000.
Output Format:
A row of data in each group, including a positive integer, indicates the number of less required sweets.
Answer description
Input example
3
1
2
2
Output example:
4
The challenge is successful. The Code is as follows:
import java.util.Scanner;public class Children { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int n = 0; int sweetCount = 0; while (cin.hasNext()) { sweetCount = 0; n = cin.nextInt(); int[] ratings = new int[n]; for (int i = 0; i < n; i++) { ratings[i] = cin.nextInt(); } int[] sweets = new int[n]; sweets[n - 1] = 1; for (int i = n - 1; i > 0; i--) { int j = i; if (ratings[j] < ratings[j - 1]) { sweets[j - 1] = sweets[j] + 1; } else if (ratings[j] == ratings[j - 1]) { sweets[j - 1] = 1; } else { if (sweets[j] == 1) { for (int k = j; k < n; k++) { sweets[k]++; if (k == n - 1 || ratings[k] >= ratings[k + 1] || (ratings[k] < ratings[k + 1] && sweets[k] < sweets[k + 1])) break; } } sweets[j - 1] = 1; } } for (int i : sweets) { sweetCount += i; } System.out.println(sweetCount); } cin.close(); }}
Programming challenges college clubs distribute candy answers