Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 1423 · Prefix / Circular Window

Maximum Points You Can Obtain from Cards

LeetCode 1423 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

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

మధ్యస్థంArraySliding WindowPrefix Sum
LeetCode లో తెరవండి ↗

నేను Maximum Points You Can Obtain from Cards (LeetCode 1423) ను ఇలా పరిష్కరించాను — Prefix / Circular Window ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, 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.

నేను ఎలా పరిష్కరించాను

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
స్టెప్-త్రూ లోడ్ అవుతోంది…

Maximum Points You Can Obtain from Cards — తరచూ అడిగే ప్రశ్నలు

Maximum Points You Can Obtain from Cards వెనుక ఉన్న 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.

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.

Maximum Points You Can Obtain from Cards యొక్క time, space complexity ఎంత?

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

Maximum Points You Can Obtain from Cards లో సాధారణ పొరపాట్లు ఏమిటి?

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