简繁EN

LeetCodeNo. 116

[LeetCode with Python] 135. Candy

Contents

Problem

Problem page: https://leetcode.com/problems/candy/
Topics: Greedy
Difficulty: Hard

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?


Analysis

I use a greedy algorithm. I start with an array of size N filled with 1s, since each child gets at least one candy. Then I make two greedy passes:

  1. First I go from left to right. If a child's rating is higher than their left neighbor's, I give them one more candy than their left neighbor.
  2. Next I go from right to left. If a child's rating is higher than their right neighbor's, they need at least one more candy than their right neighbor. Of course, if they already have more candies than their right neighbor, I leave their count alone.

(I wonder how to prove that the greedy algorithm gives an optimal solution.)


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
# @param ratings, a list of integer
# @return an integer
def candy(self, ratings):
len_r = len(ratings)
if len_r <= 1:
return len_r
candys = [1] * len_r
candys[0] = 1
candys[len_r - 1] = 1
for i in range(1, len_r):
if ratings[i] > ratings[i - 1]:
candys[i] = candys[i - 1] + 1
for i in range(len_r - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
candys[i] = max(candys[i + 1] + 1, candys[i])
return sum(candys)

Article link: https://xnerv.wang/en/leetcode-candy/