DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Maximum points you can obtain from cards

Problem
this falls under pattern 1: since the window size is constant
We will be using two pointers left and right

class Solution {
    public int maxScore(int[] cardPoints, int k) {
        //we can pick elements from left or right but the length of the picked elements should equal to k only
        int sum = 0;
        //initially we assume the max sum to be sum of k elements from the left
        for(int left =0;left<k;left++){
            sum+=cardPoints[left];
        }
        int maxSum = sum;
        //after this we will try to find out if addition of any element from the right end will make the sum more than the current max sum
        int right =cardPoints.length-1;
        for(int left=k-1;left>=0;left--){
            sum = sum-cardPoints[left]; // move left index from k-1,k-2,....till 0
            sum+=cardPoints[right];
            right--; // move right index to n-1, n-2,....
            maxSum = Integer.max(sum,maxSum);
        }

        return maxSum;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)