We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
Difficulty: 困难
Related Topics: 贪心, 数组
n 个孩子站成一排。给你一个整数数组 ratings 表示每个孩子的评分。
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
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) };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
135. 分发糖果
Description
Difficulty: 困难
Related Topics: 贪心, 数组
n
个孩子站成一排。给你一个整数数组ratings
表示每个孩子的评分。你需要按照以下要求,给这些孩子分发糖果:
1
个糖果。请你给每个孩子分发糖果,计算并返回需要准备的 最少糖果数目 。
示例 1:
示例 2:
提示:
n == ratings.length
Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: