Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

135. 分发糖果 #37

Open
webVueBlog opened this issue Sep 12, 2022 · 0 comments
Open

135. 分发糖果 #37

webVueBlog opened this issue Sep 12, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

135. 分发糖果

Description

Difficulty: 困难

Related Topics: 贪心, 数组

n 个孩子站成一排。给你一个整数数组 ratings 表示每个孩子的评分。

你需要按照以下要求,给这些孩子分发糖果:

  • 每个孩子至少分配到 1 个糖果。
  • 相邻两个孩子评分更高的孩子会获得更多的糖果。

请你给每个孩子分发糖果,计算并返回需要准备的 最少糖果数目

示例 1:

输入:ratings = [1,0,2]
输出:5
解释:你可以分别给第一个、第二个、第三个孩子分发 2、1、2 颗糖果。

示例 2:

输入:ratings = [1,2,2]
输出:4
解释:你可以分别给第一个、第二个、第三个孩子分发 1、2、1 颗糖果。
     第三个孩子只得到 1 颗糖果,这满足题面中的两个条件。

提示:

  • n == ratings.length
  • 1 <= n <= 2 * 104
  • 0 <= ratings[i] <= 2 * 104

Solution

Language: JavaScript

/**
 * @param {number[]} ratings
 * @return {number}
 */
// 两次遍历
// 从左向右遍历,保证右边大于左边
// 从右向左遍历,保证左边大于右边
var candy = function(ratings) {
    const len = ratings.length
    const candies = new Array(len).fill(1)

    for (let i = 1; i < len; i++) {
        if (ratings[i-1] < ratings[i]) {
            candies[i] = candies[i-1] + 1
        }
    }

    for (let i = len - 2; i >= 0; i--) {
        if (ratings[i] > ratings[i+1]) {
            candies[i] = Math.max(candies[i], candies[i+1] + 1)
        }
    }

    return candies.reduce((a, b) => a + b)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant