请计算最少需要多少颗糖果,才能完成上述分配。
4
挑战成功,代码如下:
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(); } }
原文地址:http://blog.csdn.net/tang9140/article/details/39318287