【LeetCode】Candy 解題報告

來源:互聯網
上載者:User

【題目】

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] 變小。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.