135. Candy

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:
1、Each child must have at least one candy.
2、Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?

class Solution {
public:
    int candy(vector<int>& ratings) {
        int n = ratings.size();
        vector<int> cans(n,1);
        
        for(int i=1;i<n;i++)
        {
            if(ratings[i]>ratings[i-1])
                cans[i] = cans[i-1] + 1;
        }
        for(int i=n-2;i>=0;i--)
        {
            if(ratings[i]>ratings[i+1]&&cans[i]<=cans[i+1])
                cans[i] = cans[i+1] + 1;
        }
        int result = 0 ;
        for(int i=0;i<n;i++)
        {
            result += cans[i];
        }
        return result;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,669評(píng)論 5 6
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa閱讀 9,066評(píng)論 0 6
  • 古代的文學(xué)放在當(dāng)今社會(huì),就會(huì)變成骸骨了嗎?現(xiàn)代的社會(huì)發(fā)展太快,古時(shí)候那一套又是不是不再適用?多學(xué)就會(huì)浪費(fèi)時(shí)間呢? ...
    kww007閱讀 602評(píng)論 0 0
  • 我是日記星球的114號(hào)星寶寶,這是我的第78篇原創(chuàng)日記。 一個(gè)市場(chǎng)戰(zhàn)神。 一個(gè)敬畏生命,敬畏健康的大咖,一天一個(gè)城...
    書香天使閱讀 620評(píng)論 0 1

友情鏈接更多精彩內(nèi)容