视频链接: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; } }