LeetCode has one question per day 1423. The maximum number of points that can be obtained

1423. Maximum points available

Several cards are arranged in a row, and each card has a corresponding point. Points an array of integers cardPointsis given.

Every action you can take a card from the beginning of the end of the line or, eventually you have to just take kcards cards.

Your points are the sum of the points of all the cards in your hand.

To give you an array of integers cardPointsand integer k, please return the maximum number of points you can get in.

Example 1:

输入:cardPoints = [1,2,3,4,5,6,1], k = 3
输出:12
解释:第一次行动,不管拿哪张牌,你的点数总是 1 。但是,先拿最右边的卡牌将会最大化你的可获得点数。最优策略是拿右边的三张牌,最终点数为 1 + 6 + 5 = 12

Example 2:

输入:cardPoints = [2,2,2], k = 2
输出:4
解释:无论你拿起哪两张卡牌,可获得的点数总是 4

Example 3:

输入:cardPoints = [9,7,7,9,7,7,9], k = 7
输出:55
解释:你必须拿起所有卡牌,可以获得的点数为所有卡牌的点数之和。

Example 4:

输入:cardPoints = [1,1000,1], k = 1
输出:1
解释:你无法拿到中间那张卡牌,所以可以获得的最大点数为 1

Example 5:

输入:cardPoints = [1,79,80,1,1,1,200,1], k = 3
输出:202

prompt:

  • 1 <= cardPoints.length <= 10^5
  • 1 <= cardPoints[i] <= 10^4
  • 1 <= k <= cardPoints.length

Method one: sliding window

Problem-solving ideas

  • Still thinking sliding window, assuming acquire a left kcards, and the number of points in mind to do pre, so the results ans = pre.
  • Then move the "window" and subtract the points of the card on the left each time; add the points of the card on the right to get the new sum of points pre, soans = max(ans, pre)
  • Repeat the previous step ktimes, come to the largest sum of points.

Reference Code

public int maxScore(int[] cardPoints, int k) {
    
    
    int n = cardPoints.length;
    int pre = 0;
    for (int i = 0; i < k; i++) {
    
    
        pre += cardPoints[i];
    }
    int ans = pre;
    for (int i = n - 1; i >= n - k; i--) {
    
    
        pre = pre + cardPoints[i] - cardPoints[k + i - n];
        ans = Math.max(ans, pre);
    }
    return ans;
}

Results of the
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_27007509/article/details/113716404