Candy

https://leetcode.com/problems/candy/
给定一个int数组,每个int代表一个小孩手中的数字,给每个小孩分糖果,保证相邻的小孩中,手中数字大的小孩拿到的糖果大于手中数字小的小孩,请问最终最少需要多少糖果。(每个小孩至少有一个糖果)

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.
  • Example 1:
    Input: [1,0,2]
    Output: 5
    Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
  • Example 2:
    Input: [1,2,2]
    Output: 4
    Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
    The third child gets 1 candy because it satisfies the above two conditions.

解题思路

单独一个数组dp记录每个小孩的糖果数量

  • 初始化每个小孩的糖果数量为1
  • 正向遍历,保证邻居下一个小孩如果数字大,糖果一定高
  • 反向遍历,保证上一个小孩如果数字大,糖果一定高
  • 反向遍历的时候有个特例的情况,需要保证i-1的大小不会完全收到i的限制dp[i - 1] = Math.max(dp[i - 1], dp[i] + 1);,用这个例子可以看看区别:input = [1,3,4,5,2]

上代码

public int candy(int[] ratings) {
        int len = ratings.length;
        int[] dp = new int[len];
        Arrays.fill(dp, 1);
        for (int i = 0; i < len - 1; i++) {
            if (ratings[i + 1] > ratings[i]) {
                dp[i + 1] = dp[i] + 1;
            }
        }

        for (int i = len - 1; i > 0; i--) {
            if (ratings[i - 1] > ratings[i]) {
                dp[i - 1] = Math.max(dp[i - 1], dp[i] + 1);
//                dp[i - 1] = dp[i] + 1; //这个不对,input 用[1,3,4,5,2] 可以看出端倪
            }
        }

        int res = 0;
        for (int i = 0; i < len; i++) {
            res += dp[i];
        }
        return res;
    }

你可能感兴趣的:(Candy)