This is part of a series of Leetcode solution explanations (index). If you liked this solution or found it useful, please like this post and/or upvote my solution post on Leetcode's forums. Leetcode Problem #1423 (Medium): Maximum Points You Can Obtain from CardsDescription:
Examples:
Constraints:
Idea:
Since we're forced to take K amount of cards no matter what, we can solve this problem with a two-pointer system with a sliding window approach. Instead of counting the sum of the values between the two pointers, we'll instead be counting the sum of the values outside the sliding window. We can start by iterating through the first K cards of our card list (C) and finding the total points. At this point, our reverse window will be the cards from i = K to j = C.length - 1. At each iteration, we'll slide the window backwards, removing one card from the left side (-C[i]) and adding one card from the right side (+C[j]) each time. We should keep track of the best possible result at each iteration, then return best once we reach the end.
Javascript Code:
Enter fullscreen mode Exit fullscreen mode Python Code:
Enter fullscreen mode Exit fullscreen mode Java Code:
Enter fullscreen mode Exit fullscreen mode C++ Code:
Enter fullscreen mode Exit fullscreen mode |