1. 程式人生 > >leetcode135 - Candy - hard

leetcode135 - Candy - hard

ret ons minimum style The inpu mini 不能 least

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?
Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.

實現題(貪婪法)
1.給所有孩子一顆糖。
2.從左到右遍歷,把當前分數和左邊比,如果高了,比左邊的糖多一顆。
3.從右到左遍歷,把當前分數和右邊比,如果高了,比右邊的糖多一顆。
4.再掃一遍計數。

細節:
1.第三步的時候,如果要和右邊比,一定要從右到左掃,不能從左到右掃。如果從左到右,因為你右邊的對象還沒有跟右邊的右邊的對象對比過,它的值都還不是確定的,你怎麽能直接拿過來計算結果呢,錯誤。比如分數321,在和右邊數對比的時候,從左到右掃就會是111->111->221錯誤,從右到左掃會是111->111->321正確
2.給所有孩子一顆糖有優雅點的寫法: Arrays.fill(array, 1);

實現:

class Solution {
    public int candy(int[] ratings) {
        if (ratings == null || ratings.length == 0) {
            return 0;
        }
        int[] candies = new int[ratings.length];
        
        // P2: 一個優雅的填充寫法。
        Arrays.fill(candies, 1);
        // for (int i = 0; i < candies.length; i++) {
        
// candies[i] = 1; // } for (int i = 1; i < candies.length; i++) { if (ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) { candies[i] = candies[i- 1] + 1; } } // P1: 和右邊的數字對比的時候,要從右到左遍歷,否則會出錯,比如321的孩子,在和右邊數對比的時候,從左到右掃就會是111->111->221,從右到左掃會是111->111->321正確 for (int i = candies.length - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) { candies[i] = candies[i + 1] + 1; } } int ans = 0; for (int i = 0; i < candies.length; i++) { ans += candies[i]; } return ans; } }

leetcode135 - Candy - hard