Given N cards arranged in a row, each card has an associated score denoted by the cardScore array. Choose exactly k cards. In each step, a card can be chosen either from the beginning or the end of the row. The score is the sum of the scores of the chosen cards.
Return the maximum score that can be obtained.
Input : cardScore = [1, 2, 3, 4, 5, 6] , k = 3
Output : 15
Explanation : Choosing the rightmost cards will maximize your total score. So optimal cards chosen are the rightmost three cards 4 , 5 , 6.
Th score is 4 + 5 + 6 => 15.
Input : cardScore = [5, 4, 1, 8, 7, 1, 3 ] , k = 3
Output : 12
Explanation : In first step we will choose card from beginning with score of 5.
In second step we will choose the card from beginning again with score of 4.
In third step we will choose the card from end with score of 3.
The total score is 5 + 4 + 3 => 12
Input : cardScore = [9, 10, 1, 2, 3, 5] , k = 5
Here, the idea is to use a window of size k
, first calculate the sum of k elements from the beginning. Then, maintain the window size of k by subtracting the beginning elements from the calulated sum one by one and adding the elements from the end of the array. Everytime while doing so we will keep track of the maximum sum encountered so far. This process will continue till we have subtracted all k elements from the beginning of the array from the sum, thus ensuring that we have taken every possible case in consideration.
lSum
, rSum
, maxSum
and initialize them to 0.rightIndex
as sizeOfArray - 1 to iterate the array from last. Then, initialize a loop say(i) from k-1 to 0. Inside this loop update rSum, lSum and maxSum accordingly and finally return maxSum as our answer.Please refer to the video for complete dry-run.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to calculate the maximum
score after picking k cards*/
int maxScore(vector<int>& cardScore, int k) {
int lSum = 0, rSum = 0, maxSum = 0;
// Calculate the initial sum of the first k cards
for (int i = 0; i < k; i++) {
lSum += cardScore[i];
/* Initialize maxSum with the
sum of the first k cards*/
maxSum = lSum;
}
//Initialize rightIndex to iterate array from last
int rightIndex = cardScore.size() - 1;
for (int i = k - 1; i >= 0; i--) {
// Remove the score of the ith card from left sum
lSum -= cardScore[i];
/* Add the score of the card
from the right to the right sum*/
rSum += cardScore[rightIndex];
// Move to the next card from the right
rightIndex--;
// Update maxSum with the maximum sum found so far
maxSum = max(maxSum, lSum + rSum);
}
// Return the maximum score found
return maxSum;
}
};
int main() {
vector<int> nums = {1, 2, 3, 4, 5, 6};
// Create an instance of the Solution class
Solution sol;
int result = sol.maxScore(nums, 3);
// Output the maximum score
cout << "The maximum score is:\n";
cout << result << endl;
return 0;
}
import java.util.*;
class Solution {
/* Function to calculate the maximum
score after picking k cards */
public int maxScore(int[] cardScore, int k) {
int lSum = 0, rSum = 0, maxSum = 0;
// Calculate the initial sum of the first k cards
for (int i = 0; i < k; i++) {
lSum += cardScore[i];
/* Initialize maxSum with the
sum of the first k cards */
maxSum = lSum;
}
// Initialize rightIndex to iterate array from last
int rightIndex = cardScore.length - 1;
for (int i = k - 1; i >= 0; i--) {
// Remove the score of the ith card from left sum
lSum -= cardScore[i];
/* Add the score of the card
from the right to the right sum */
rSum += cardScore[rightIndex];
// Move to the next card from the right
rightIndex--;
// Update maxSum with the maximum sum found so far
maxSum = Math.max(maxSum, lSum + rSum);
}
// Return the maximum score found
return maxSum;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6};
// Create an instance of the Solution class
Solution sol = new Solution();
int result = sol.maxScore(nums, 3);
// Output the maximum score
System.out.println("The maximum score is:");
System.out.println(result);
}
}
class Solution:
""" Function to calculate the maximum
score after picking k cards"""
def maxScore(self, cardScore, k):
lSum = 0
rSum = 0
maxSum = 0
# Calculate the initial sum of the first k cards
for i in range(k):
lSum += cardScore[i]
""" Initialize maxSum with the
sum of the first k cards"""
maxSum = lSum
# Initialize rightIndex to iterate array from last
rightIndex = len(cardScore) - 1
for i in range(k - 1, -1, -1):
# Remove the score of the ith card from left sum
lSum -= cardScore[i]
# Add the score of the card
# from the right to the right sum
rSum += cardScore[rightIndex]
# Move to the next card from the right
rightIndex -= 1
# Update maxSum with the maximum sum found so far
maxSum = max(maxSum, lSum + rSum)
# Return the maximum score found
return maxSum
nums = [1, 2, 3, 4, 5, 6]
# Create an instance of the Solution class
sol = Solution()
result = sol.maxScore(nums, 3)
# Output the maximum score
print("The maximum score is:")
print(result)
class Solution {
// Function to calculate the maximum
// score after picking k cards
maxScore(cardScore, k) {
let lSum = 0, rSum = 0, maxSum = 0;
// Calculate the initial sum of the first k cards
for (let i = 0; i < k; i++) {
lSum += cardScore[i];
/* Initialize maxSum with the
sum of the first k cards */
maxSum = lSum;
}
// Initialize rightIndex to iterate array from last
let rightIndex = cardScore.length - 1;
for (let i = k - 1; i >= 0; i--) {
// Remove the score of the ith card from left sum
lSum -= cardScore[i];
/* Add the score of the card
from the right to the right sum */
rSum += cardScore[rightIndex];
// Move to the next card from the right
rightIndex--;
// Update maxSum with the maximum sum found so far
maxSum = Math.max(maxSum, lSum + rSum);
}
// Return the maximum score found
return maxSum;
}
}
let nums = [1, 2, 3, 4, 5, 6];
// Create an instance of the Solution class
let sol = new Solution();
let result = sol.maxScore(nums, 3);
// Output the maximum score
console.log("The maximum score is:");
console.log(result);
Q: Why is the sliding window approach optimal?
A: The sliding window ensures that each combination of i cards from the front and k−i cards from the back is considered without recomputing sums from scratch, reducing the time complexity.
Q: How would you modify this to allow choosing non-consecutive cards?
A: For non-consecutive cards, the problem becomes a combinatorial selection problem, requiring dynamic programming or backtracking to explore all possible subsets of size k.
Q: How would you handle multiple players selecting cards alternately?
A: Modify the algorithm to account for alternating turns by simulating the selection process for both players, optimizing for one while considering the opponent’s moves.