【題目】
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?
【題意】
多個小朋友站成一排,根據他們的得分分發糖果,得分高的小朋友要比旁邊得分低的小朋友得到的糖果多,每個小朋友至少得到一枚糖果,問最少要準備多少糖果。
【思路】
先從左至右掃描一遍,使得右邊比左邊得分高的小朋友糖果數比左邊多。
再從右至左掃描一遍,使得左邊比右邊得分高的小朋友糖果數比右邊多。
【Java代碼】
public class Solution { public int candy(int[] ratings) { int size = ratings.length; if (size == 0) return -1; if (size == 1) return 1; int[] cans = new int[size]; cans[0] = 1; //正向掃描一遍,如果右邊的rating比左邊高,那麼右邊的糖果數就比左邊多一個,否則只給一個糖果 for (int i = 1; i < size; i++) { if (ratings[i] > ratings[i - 1]) cans[i] = cans[i - 1] + 1; else cans[i] = 1; } //反向掃描一遍,如果左邊的rating比右邊高,並且左邊的糖果數比右邊少,那麼左邊的糖果數應比右邊多一 for (int i = size - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1] && cans[i] <= cans[i + 1]) { cans[i] = cans[i + 1] + 1; } } int ret = 0; for (int i = 0; i < size; i++) { ret += cans[i]; } return ret; }}
這個演算法確實是自己想出來,後來發現網上也都是這麼解的,確實感到很高興。
思路雖然一下就想對了,但是提交了三四次才AC。首先是忘記判斷 (size == 1) 的情況,其實是沒有寫 (ratings[i] > ratings[i + 1] && cans[i] <= cans[i + 1]) 的後半部分的判斷,因為如果左邊糖果數本身就已經比右邊多了,那麼改成 cans[i] = cans[i + 1] + 1; 就有可能把 cans[i] 變小。