6 Candy_Leetcode

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:ui

  • 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?spa

舉個例子,1 3 2 7 5 4 2blog

第一眼咱們確定會想到讓一些波谷(1, 3, 2)的糖果個數爲1, 而後依次從這些值往左和往右擴張填充。若是隻能想到模擬的方法,那這題基本無法作。rem

這裏值得強調的是,通常狀況下,面試要考察的都不會是簡單的模擬。get

除了與左邊和右邊的鄰居比較,咱們還能怎麼理解這個問題呢?it

若是從定序的角度來看,咱們能夠從左到右和從右到左遍歷這個序列,對於每個位置,它須要的糖果數量與它從某個方向看過來是第幾個連續增加的數有關。而且是從左與從右看的結果中取較大。io

有了這種「定序」的思想,找到解答的方法也就很簡單了。ast

值得注意的是,在從一個方向往另外一個方向掃描的過程當中,因爲連續相等的數值之間是不作比較的,因此相等的數能夠只發一個糖果,做爲下一個遞增序列的開始。class

Code:

class Solution {
public:
    int candy(vector<int> &ratings) {
        int n = ratings.size();
        if(n == 0) return 0;
        int sum = 0;
        
        vector<int> left(n, 1);
        vector<int> right(n, 1);
        
        for(int i = 1; i < n; i++)
        {
            if(ratings[i] > ratings[i-1]) left[i] = left[i-1] + 1;
            else left[i] = 1; // first error, when equal, no camparison, so the candy could start from 1
        }
        
        for(int j = n-2; j >= 0; j--)
        {
            if(ratings[j] > ratings[j+1]) right[j] = right[j+1] + 1;
            else right[j] = 1;
        }
        
        for(int i = 0; i < n; i++) sum += max(left[i], right[i]);
        
        return sum;
    }
};
相關文章
相關標籤/搜索