array score(C++數組得分)

解題思路:

(1)求得初始窗口的值,最後使用進一個出一個的方法,滑動求值

class Solution {
public:
    /**
     * @param nums: the array to be scored.
     * @param k: the requirement of subarray length.
     * @param u: if the sum is less than u, get 1 score.
     * @param l: if the sum is greater than l, lose 1 score.
     * @return: return the sum of scores for every subarray whose length is k.
     */
    int arrayScore(vector<int> &nums, int k, long long u, long long l) {
        int score = 0;
        long long sum = 0;
        for(int i=0;i<k;i++) sum+=nums[i];
        if(sum<u) score++;
        else if(sum>l) score--;
        for(int i=k;i<nums.size();i++) {
            sum = sum+nums[i]-nums[i-k];
            if(sum<u) score++;
            else if(sum>l) score--;
        }
        return score;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章