LeetCode:Candy糖果发放

题目描述

有N个小朋友站在一排,每个小朋友都有一个评分

你现在要按以下的规则给孩子们分糖果:

  • 每个小朋友至少要分得一颗糖果
  • 分数高的小朋友要他比旁边得分低的小朋友分得的糖果多

你最少要分发多少颗糖果?

 

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

动态规划思想:每个糖果的值都要受限与邻居结点,如果评估值比邻居结点大,那么得到的糖果也比邻居结点多,因此都需要与左右邻居结点进行比较。

Java代码

public class Solution {
    public int candy(int[] ratings) {
        if(ratings == null || ratings.length == 0)
            return 0;
        int len = ratings.length;
        int[] dp = new int[len];
        int sum = 0;
        //初始化,给每个小朋友先分发一个糖果
        for(int i = 0; i < len; i++){
            dp[i] = 1;
        }
        //从左往右遍历,右边的小朋友分数比左边的小朋友分数高,则右边分数高的小朋友糖果+1
        for(int i = 0; i < len -1; i++){
            //和左边的比较
            if(ratings[i+1] > ratings[i])
                dp[i+1] = dp[i] + 1;
        }
        //从右往左遍历,左边的小朋友分数比右边的小朋友分数高,则左边分数高的小朋友糖果+1
        for(int j = len - 2; j >= 0; j--){
            //和右边的比较
            if(ratings[j] > ratings[j+1] && dp[j] <= dp[j+1])
                dp[j] = dp[j+1] + 1;
        }
        //计算总糖果数
        for(int i = 0; i < len; i++){
            sum += dp[i];
        }
        return sum;
    }
}

 

你可能感兴趣的:(LeetCode:Candy糖果发放)