lintcode-分糖果

作者: 鬼谷神奇 | 来源:发表于2016-06-01 10:18 被阅读58次

    空间复杂度O(n)

    class Solution {
    public:
        /**
         * @param ratings Children's ratings
         * @return the minimum candies you must give
         */
        int candy(vector<int>& ratings) {
            // Write your code here
            
            vector<int> dp(ratings.size(), 1);
            
            for(int i = 1; i < dp.size(); ++i){
                if(ratings[i] > ratings[i-1]){
                    dp[i] = max(dp[i], dp[i-1] + 1);
                }
            }
            
            for(int i = dp.size() - 1; i > 0; --i){
                if(ratings[i] < ratings[i-1]){
                    dp[i-1] = max(dp[i-1], dp[i] + 1);
                }
            }
            
            return accumulate(dp.begin(), dp.end(), 0);
        }
    };
    

    空间复杂度O(1)

    class Solution {
    public:
        /**
         * @param ratings Children's ratings
         * @return the minimum candies you must give
         */
        int candy(vector<int>& ratings) {
            // Write your code here
            
            int total = 0;
            int preCount = 1;  //前一个小孩的糖果数
            int descendStartCount = preCount;  //递减序列开始的孩子的糖果数
            int length = 0;  
            
            if(ratings.size() == 0) {
                return 0;
            }
            
            total++;
            for(int i = 1; i < ratings.size(); ++i) {
                if(ratings[i] < ratings[i-1]) {
                    length ++ ;
                    if(descendStartCount <= length) {
                        total++;  //根据递减序列的长度修正递减序列第一个孩子的糖果数
                    }
                    total += length;  //逆序获取后续孩子的糖果数
                    preCount = 1;     //注意
                }else{
                    int currentCount = 0;
                    if(ratings[i] > ratings[i-1]) {
                        currentCount = preCount + 1;
                    }else{
                        currentCount = 1;
                    }
                    
                    total += currentCount;
                    preCount = currentCount;
                    length = 0;      //注意
                    descendStartCount = currentCount;
                }
            }
            
            return total;
            
        }
    };
    

    相关文章

      网友评论

        本文标题:lintcode-分糖果

        本文链接:https://www.haomeiwen.com/subject/eqacdttx.html