Leetcode#135. Candy
Problem
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.
Example 1:
1 | Input: ratings = [1,0,2] |
Example 2:
1 | Input: ratings = [1,2,2] |
Constraints:
n == ratings.length
1 <= n <= 2 * 10^4
0 <= ratings[i] <= 2 * 10^4
Solve
這題看似簡單,但意外讓我卡很久
法1
直接遍歷方式解法,(這解法不確定算不算用到greedy了)
1.每個同學都先發放一顆
2.接下來兩兩比較當下一個較大就多發一顆
3.從後面看回來,同樣的方式,比下一個大的就多發一顆,但多一個加條件,當下一個已經多發就不用改變
1 | class Solution: |
Time Complexity : O(n)
Space Complexity : O(n)
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Imisky!
評論