Max Points You Can Obtain From Cards
DESCRIPTION (credit Leetcode.com)
Given an array of integers representing the value of cards, write a function to calculate the maximum score you can achieve by selecting exactly k cards from either the beginning or the end of the array.
For example, if k = 3, then you have the option to select:
- the first three cards,
- the last three cards,
- the first card and the last two cards
- the first two cards and the last card
EXAMPLES
Example 1: Input:
cards = [2,11,4,5,3,9,2] k = 3
Output:
17
Explanation:
- Selecting the first three cards from the beginning (2 + 11 + 4) gives a total of 17.
- Selecting the last three cards (3 + 9 + 2) gives a total of 14.
- Selecting the first card and the last two cards (2 + 9 + 2) gives a total of 13.
- Selecting the first two cards and the last card (2 + 11 + 2) gives a total of 15.
So the maximum score is 17.
Run your code to see results here
Explanation
The key to this problem is recognizing that each valid arrangement of cards we can choose is equivalent to removing n - k cards from the middle of the array, where n is the length of the array.
The sum of any valid arrangement is equivalent to total sum of the array minus the sum of the n - k cards we remove.
Sum of valid arrangement = 36 - 23 = 13
So we can move the fixed-length sliding window of length n - k across the array. For each window, we subtract its sum from the total sum of the array to get the sum of the corresponding cards, and return the maximum of those values at the end.
Solution
def maxScore(cards, k):total = sum(cards)if k >= len(cards):return totalstate = 0max_points = 0start = 0for end in range(len(cards)):state += cards[end]if end - start + 1 == len(cards) - k:max_points = max(total - state, max_points)state -= cards[start]start += 1return max_points
start
max points from cards
0 / 18
1x
© 2024 Optick Labs Inc. All rights reserved.
Loading comments...