leetcodeの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:
  • 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?
    つまり、
    N人の子供が一列に並んでいて、子供一人一人に点数があります.ある子供の点数が隣人の点数より高い場合、彼が得たキャンディは隣人より多い.子供一人一人に最低1つのキャンディがもらえます.問:少なくともキャンディはいくら必要ですか.
    問題解決の考え方:
    1、まず、左の最初の子供にキャンディをあげます.左から子供の点数グループを巡り、右の子供が左より高い場合は、そばの子供にキャンディを1つ追加します.さもないと、キャンディをあげます.
    2,右から左へ回ります.左の子供の点数が右の子供より高い場合、左の子供は右の子供よりキャンディを1つ多くします.また,この子については,前回左から右へ遍歴したもの,子供のキャンディと現在更新されたもののうち,キャンディが多かったものを結果として選択した.
    コードは次のとおりです.
    class Solution {
    public:
        int candy(vector<int> &ratings) {
            	int length = ratings.size();
    			if(length == 0){
    				return 0;
    			}
    			int i;
    			vector<int> candy1;
    			candy1.push_back(1);
    			for(i=1;i<length;i++){
    				if(ratings[i] > ratings[i-1]){
    					candy1.push_back(*(candy1.end()-1) + 1);
    				}
    				else{
    					candy1.push_back(1);
    				}
    			}
    			int m = 0;
    			for(i=length-2;i>=0;i--){
    				if(ratings[i] > ratings[i+1]){
    					m = candy1[i+1] + 1;
    					if(m > candy1[i]){
    						candy1[i] = m;
    					}
    				}
    			}
    			int sum = 0;
    			for(i=0;i<length;i++){
    				sum += candy1[i];
    			}
    			return sum;
        }
    };