Candy

2020-07-28  本文已影响0人  瞬铭

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记录每个小孩的糖果数量

上代码

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;
    }
上一篇下一篇

猜你喜欢

热点阅读