Maximum Points You Can Obtain from Cards
LeetCode 1423 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Slide k picks from all-left to all-right.
मैंने 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
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.
मैंने कैसे हल किया
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 totalMaximum 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.