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

मी 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.