题解 | #分糖果问题#
分糖果问题
https://www.nowcoder.com/practice/76039109dd0b47e994c08d8319faa352
import java.util.*; public class Solution { /** * pick candy * @param arr int整型一维数组 the array * @return int整型 */ public int candy (int[] arr) { // write code here int len = arr.length; int nums[] = new int[len]; //每个孩子默认得到一个糖果 Arrays.fill(nums,1); int res = 0; for(int i = 1 ; i < len ; i++){ if(arr[i] > arr[i - 1]){ nums[i] = nums[i - 1] + 1; } } for(int j = len - 2; j >= 0 ; j--){ if(arr[j] > arr[j + 1] && nums[j] <= nums[j + 1]){ nums[j] = nums[j + 1] +1; } } for(int i = 0 ; i < len ; i++){ res +=nums[i]; } return res; } }