视频讲解
分糖果问题
http://www.nowcoder.com/questionTerminal/76039109dd0b47e994c08d8319faa352
视频链接:https://www.bilibili.com/video/BV1uz4y1U71X/
左右各遍历一次。
import java.util.*; public class Solution { /** * pick candy * @param arr int整型一维数组 the array * @return int整型 */ public int candy (int[] arr) { int res[] = new int[arr.length]; Arrays.fill(res, 1); int count = 0; for (int i = 1; i < arr.length; i++){ if (arr[i] > arr[i - 1]){ res[i] = res[i - 1] + 1; } } for (int i = arr.length - 1; i > 0; i--){ if (arr[i - 1] > arr[i]){ res[i - 1] = Math.max(res[i - 1], res[i] + 1); } } for (int i: res){ count += i; } return count; } }