Tensorum
LeetCode 1423 · Prefix / Circular Window

Maximum Points You Can Obtain from Cards

LeetCode 1423 · Medium · solution, intuition & step-by-step walkthrough

Slide k picks from all-left to all-right.

MediumArraySliding WindowPrefix Sum
63 msruntime · beats 5%
55.3 MBmemory · beats 100%
1approach
1accepted runs · last 2 May 2024

This is how I solved Maximum Points You Can Obtain from Cards (LeetCode 1423), a medium problem from the Prefix / Circular Window pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Taking k cards from the ends means taking i from the left and k − i from the right. Start with all k from the left, then move one card at a time from the left side to the right side, tracking the best total.

Approach

  1. 1

    Sum the first k cards.

  2. 2

    For i from k−1 down to 0: drop cardPoints[i] from the left sum, add the next card from the right end.

  3. 3

    Keep the maximum.

How I solved it

Two-sided windowPythonO(k) time · O(1) space
class Solution:
    def maxScore(self, cardPoints, k):
        total = 0
        lsum = 0
        rsum = 0
        n = len(cardPoints)
        for i in range(k):
            lsum += cardPoints[i]
            total = lsum
        rIndex = n - 1
        for i in range(k - 1, -1, -1):
            lsum = lsum - cardPoints[i]
            rsum += cardPoints[rIndex]
            rIndex -= 1
            total = max(total, lsum + rsum)
        return total
Loading the step-through…

Maximum Points You Can Obtain from Cards — FAQ

What is the intuition behind Maximum Points You Can Obtain from Cards?

Taking k cards from the ends means taking i from the left and k − i from the right. Start with all k from the left, then move one card at a time from the left side to the right side, tracking the best total.

How do you solve Maximum Points You Can Obtain from Cards (LeetCode 1423)?

1. Sum the first k cards. 2. For i from k−1 down to 0: drop cardPoints[i] from the left sum, add the next card from the right end. 3. Keep the maximum.

What is the time and space complexity of Maximum Points You Can Obtain from Cards?

Time: O(k). Space: O(1). (Accepted approach: Two-sided window.)

What are common mistakes in Maximum Points You Can Obtain from Cards?

Equivalent: minimise the middle window of length n − k.