美文网首页
135. Candy

135. Candy

作者: lqsss | 来源:发表于2018-03-26 21:56 被阅读0次

题目

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?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?

思路

dp[i]:记录i的获取糖果树

  1. 从左向右扫描,保证一个方向上分数更大的糖果更多
  2. 从右向左扫描,保证另一个方向上分数更大的糖果更多

代码

public class Candy {
    public static int candy(int[] ratings) {
        int[] dp = new int[ratings.length];
        for (int i = 0; i < dp.length; i++) {
            dp[i] = 1;
        }
        

        for (int i = 1; i < dp.length; i++) {
            if (ratings[i] > ratings[i - 1]) {
                dp[i] = dp[i - 1] + 1;
            }
        }
        

        for (int i = dp.length - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1] && dp[i] <= dp[i + 1]) {
                dp[i] = dp[i + 1] + 1;
            }
        }

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

        return res;
    }

/*    public static void main(String[] args) {
        candy(new int[]{2,2});
    }*/
}

相关文章

  • 135. Candy [Hard] DP

    135. Candy

  • 经典算法题:分发糖果

    135. 分发糖果[https://leetcode.cn/problems/candy/] 难度:困难 n 个孩...

  • 135. Candy

    题目 思路 dp[i]:记录i的获取糖果树 从左向右扫描,保证一个方向上分数更大的糖果更多 从右向左扫描,保证另一...

  • 135. Candy

    题目分析 There are N children standing in a line. Each child ...

  • 135. Candy

    There are N children standing in a line. Each child is as...

  • 135. Candy

    题目描述:N个孩子坐在一排,每个孩子分配一个等级值,按如下要求给每个孩子分糖: 每个孩子至少有一个 等级高的孩子比...

  • 135. Candy

    There are N children standing in a line. Each child is as...

  • 135. Candy

    问题分析 There are N children standing in a line. Each child ...

  • 135. Candy

    根据题意及贪心思想:评分高的学生必须获得更多的糖果 等价于 所有学生满足左规则且满足右规则

  • 135. Candy

    Ref: https://leetcode-cn.com/problems/candy/[https://leet...

网友评论

      本文标题:135. Candy

      本文链接:https://www.haomeiwen.com/subject/zvsdcftx.html