zoukankan      html  css  js  c++  java
  • 135. Candy(Array; Greedy)

    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?

    思路:neighbor=>元素值与前、后元素有关=> 需要前向、后向两次扫描

    第一次前向扫描:保证high rate元素比左邻居糖多;

    第二次后向扫描:保证high rate元素比右邻居糖多;

    class Solution {
    public:
        int candy(vector<int> &ratings) {
            vector<int> new_ratings(ratings.size(), 1);
            for(int i = 1; i < ratings.size(); i++) //for the first time, scan from beginning
            {
                if(ratings[i] > ratings[i-1]) 
                {
                    new_ratings[i] = new_ratings[i-1]+1;
                }
              
            }
            for(int i=ratings.size()-2;i>=0;i--){  //for the second time, scan from the end
                if(ratings[i]>ratings[i+1]&&new_ratings[i]<=new_ratings[i+1]){  
                    new_ratings[i]=new_ratings[i+1]+1;  
                }  
            }  
            int sum=0;  
            for(int i=0;i<new_ratings.size();i++){  
                sum+=new_ratings[i];  
            }  
              
            return sum;  
        }
    };
  • 相关阅读:
    浅谈折半搜索
    NOIP PJ/CSP-J 题目选做
    SDN第五次上机作业
    SDN第四次上机作业
    SDN第三次上机作业
    SDN第二次上机作业
    必看
    关于tensor
    permute与transpose
    1823. 找出游戏的获胜者
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4853463.html
Copyright © 2011-2022 走看看