← Home

1423. Maximum Points You Can Obtain from Cards

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
142

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1423. Maximum Points You Can Obtain from Cards, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, two pointers, sliding window.

The notes already sitting in the source point us in the right direction:

  • MLE
  • 26 / 40 test cases passed.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are maxScore.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//MLE
02//26 / 40 test cases passed.
03class Solution {
04public:
05    int maxScore(vector<int>& cardPoints, int k) {
06        int n = cardPoints.size();
07        if(n <= k) return accumulate(cardPoints.begin(), cardPoints.end(), 0);
08        cardPoints.insert(cardPoints.begin(), 0);
09        cardPoints.push_back(0);
10        
11        vector<vector<int>> last(n+2, vector(k+1, 0));
12        vector<vector<int>> cur(n+2, vector(k+1, 0));
13        
14        for(int width = 1; width <= n; width++){
15            for(int left = 1; left + width -1 <= n; left++){
16                int right = left + width -1;
17                for(int taken = 1; taken <= min(k, right-left+1); taken++){
18                    cur[left][taken] = max({cur[left][taken],
19                        last[left+1][taken-1] + cardPoints[left],
20                        last[left][taken-1] + cardPoints[right]});
21                    // cout << left << " " << right << " " << taken << " " << dp[left][right][taken] << endl;
22                    swap(last, cur);
23                    cur = vector<vector<int>>(n+2, vector(k+1, 0));
24                }
25            }
26        }
27        
28        // return last[n][k];
29        return cur[n][k];
30    }
31};
32
33//DP+Sliding window
34//Runtime: 148 ms, faster than 76.21% of C++ online submissions for Maximum Points You Can Obtain from Cards.
35//Memory Usage: 42.5 MB, less than 100.00% of C++ online submissions for Maximum Points You Can Obtain from Cards.
36class Solution {
37public:
38    int maxScore(vector<int>& cardPoints, int k) {
39        int n = cardPoints.size();
40        //the remaining cards must be continuous
41        int remainCount = n - k;
42        int remainSum = accumulate(cardPoints.begin(), cardPoints.begin()+n-k, 0);
43        int minRemainSum = remainSum;
44        int totalSum = remainSum;
45        
46        for(int i = n-k; i < n; i++){
47            remainSum += (cardPoints[i] - cardPoints[i-(n-k)]);
48            minRemainSum = min(minRemainSum, remainSum);
49            totalSum += cardPoints[i];
50        }
51        
52        return totalSum - minRemainSum;
53    }
54};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.