Candy

https://leetcode.com/problems/candy/
給定一個int數(shù)組,每個int代表一個小孩手中的數(shù)字,給每個小孩分糖果,保證相鄰的小孩中,手中數(shù)字大的小孩拿到的糖果大于手中數(shù)字小的小孩,請問最終最少需要多少糖果。(每個小孩至少有一個糖果)

  • 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.

解題思路

單獨一個數(shù)組dp記錄每個小孩的糖果數(shù)量

  • 初始化每個小孩的糖果數(shù)量為1
  • 正向遍歷,保證鄰居下一個小孩如果數(shù)字大,糖果一定高
  • 反向遍歷,保證上一個小孩如果數(shù)字大,糖果一定高
  • 反向遍歷的時候有個特例的情況,需要保證i-1的大小不會完全收到i的限制dp[i - 1] = Math.max(dp[i - 1], dp[i] + 1);,用這個例子可以看看區(qū)別: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;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容