Sliding Window: Maximum points you can obtain from cards

Problem Statement:

There are cards that are arranged in a row, each card has a number of points.

The points are given in the integer array cardPoints.

You can take one card either beginning or from end of the row, and you have to exactly take k cards.

The score is the sum of the points of the cards that has been taken out.

Example:

Input:  cardScore = [1, 2, 3, 4, 5, 6] k = 3

Output: 15

You can remove 4, 5, 6 whose sum is 15

Solution Explanation:

Take a window of size k.

Since we can select from either from start or from end, then we have to access either the first k times or last k items.

Time Complexity: O(1)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#include <algorithm>
#include <climits>
using namespace std;


int solution(vector<int>& cardPoints, int k) 
{
    int res = 0;
	
    for(int i=0; i < k; i++) 
    	res += cardPoints[i];
    
    int curr=res;

    for(int i = k-1; i >= 0; i--) 
    {
        curr -= cardPoints[i];
        curr += cardPoints[cardPoints.size()-k+i];
		
		res = max(res, curr);
    }
    
    return res;
}

int main()
{
    vector<int> cardPoints = {1, 2, 3, 4, 5, 6};
    int k = 3;

    cout << solution(cardPoints, k) << endl;

    return 0;
}

Output
————-

15
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *