【LeetCode 面试经典150题】135. Candy 分发糖果

135. Candy

题目大意

There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.

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.

Return the minimum number of candies you need to have to distribute the candies to the children.

中文释义

一排站着 n 个孩子。每个孩子都被分配了一个整数数组 ratings 中的评分值。

你需要给这些孩子分发糖果,但需遵守以下要求:

  • 每个孩子至少分到一颗糖果。
  • 评分更高的孩子比他们的邻居获得更多的糖果。

返回你需要拥有的最少糖果数量,以便将糖果分发给孩子们。

Example

Example 1:

  • Input: ratings = [1,0,2]
  • Output: 5
  • Explanation: 你可以分别给第一个、第二个和第三个孩子分发 2, 1, 2 颗糖果。

Example 2:

  • Input: ratings = [1,2,2]
  • Output: 4
  • Explanation: 你可以分别给第一个、第二个和第三个孩子分发 1, 2, 1 颗糖果。第三个孩子分到 1 颗糖果,因为它满足上述两个条件。

Constraints

  • n == ratings.length
  • 1 <= n <= 2 * 10^4
  • 0 <= ratings[i] <= 2 * 10^4

解题思路

算法描述

这段代码的目的是分配糖果给一排孩子,满足评分较高的孩子比其邻居获得更多的糖果。

  • 首先初始化数组每个孩子获得糖果数为1。

  • 从左至右遍历,判断当前孩子和左边的孩子相比,如果当前孩子评分更高,那么当

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值