LeetCode 1423. Maximum points available

LeetCode 1423. Maximum points available

1. Topic

Insert picture description here

Insert picture description here
Insert picture description here


Two, ideas

The sliding window idea
first saves the sum of the first k values ​​of the array as the initial value of the window, and then the window slides to the right one at a time, the value of the sliding window subtracts the old leftmost value, plus the value of the newly added window, here Save the maximum value during the process

Note that the condition of traversing the array is not to move to the end of the array, but to stop when moving to the kth, because the title says that it can only be taken from the leftmost and rightmost


Three, code implementation (Java)

class Solution {
    
    
    public int maxScore(int[] cardPoints, int k) {
    
    
        int cnt = 0;
        int len = cardPoints.length;
        for(int i = 0; i<k; i++) {
    
    
            cnt += cardPoints[i];  //窗口初始值
        }
        int res = cnt;
        for(int i = 0; i<k; i++) {
    
    
            cnt += cardPoints[len-i-1];  //窗口加入新的最右边的值
            cnt -= cardPoints[k-i-1];    //窗口减去旧的最左边的值
            res = Math.max(res,cnt);
        }
        return res;
    }
}

Insist on sharing, insist on originality, pretty girls who like bloggers can check out the blogger's homepage blog!
Your likes and favorites are my greatest appreciation for sharing blogs!
Blogger blog address: https://blog.csdn.net/weixin_43967679

Guess you like

Origin blog.csdn.net/weixin_43967679/article/details/113726218