maxScore-the maximum number of points available

Title

Several cards are arranged in a row, and each card has a corresponding point. The number of points is given by the integer array cardPoints.

For each action, you can take a card from the beginning or the end of the line, and in the end you must take exactly k cards.

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

Give you an integer array cardPoints and an integer k, please return the maximum number of points you can get.

Example 1:

Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
Explanation: In the first action, no matter which card you take, your point is always 1. However, taking the rightmost card first will maximize your available points. The optimal strategy is to take the three cards on the right, and the final point is 1 + 6 + 5
= 12.

Example 2:

Input: cardPoints = [2,2,2], k = 2
Output: 4
Explanation: No matter which two cards you pick up, the number of points you can get is always 4.

Example 3:

Input: cardPoints = [9,7,7,9,7,7,9], k = 7
Output: 55
Explanation: You must pick up all the cards, and the points you can get are the sum of the points of all the cards.

Example 4:

Input: cardPoints = [1,1000,1], k = 1
Output: 1
Explanation: You cannot get the card in the middle, so the maximum number of points you can get is 1.

Example 5:

Input: cardPoints = [1,79,80,1,1,1,200,1], k = 3
Output: 202

prompt:

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

Related Topics Array Dynamic Programming Sliding Window

Problem-solving ideas

The question suggests that using a sliding window can solve the problem. The
sliding window is nothing more than expansion and translation.
Continuously take a card from the beginning or the end of the line. If the k value is fixed, the position of the remaining nk cards must be continuous and fixed.
Reverse thinking , The maximum value in the question is to find the minimum value of (nk) in the window

Code demo

class Solution {
    
    
    public int maxScore(int[] cardPoints, int k) {
    
    
       int n=cardPoints.length;
       //记录所有卡牌的和
       int sum=0;
       //记录当前窗口中的值
       int Wnum=0;
       //保留窗口中的最小值
       int min=0;
       //求第一个窗口的值
        for (int i = 0; i < n - k; i++) {
    
    
            sum+=cardPoints[i];
        }
        Wnum=sum;
        min=sum;
        for(int i=n-k;i<n;i++)
        {
    
    
            sum+=cardPoints[i];
            Wnum-=cardPoints[i-n+k];
            Wnum+=cardPoints[i];
            if(Wnum < min)
                min=Wnum;
        }
        return sum-min;
    }
}

running result

The info
answer was successful:
execution time: 2 ms, defeating 95.77% of Java users
Memory consumption: 47.8 MB, defeating 35.59% of Java users

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/113716265