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.