DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Maximum Points You Can Obtain from Cards

Maximum Points You Can Obtain from Cards

Approach

We have to calculate sum of K elements from array & you can take one card from the beginning or from the end of the row. You have to take exactly k cards.

What we will do is we will create a window of arr.length - k let windowLength = arr.length - k;, so after this we will be left with on K elemnts in array & sum of those K will give us ans.

At first, we will take sum of all remaining K elements after window. i.e

example arr = [1, 2, 3, 4, 5, 6, 1], length = 7 & K = 3
so windowLength should be of 7-3 = 4 element => [1, 2, 3, 4]
now remaining k (i.e 3) element = [5, 6, 1],

for (let i = windowLength; i < arr.length; i++) {
windowSum = windowSum + arr[i];
}

& will assume that this sum is maximum sum.

Now for this statement "you can take one card from the beginning or from the end of the row. You have to take exactly k cards."

We will add one element from start to maxsum & will move window by 1 element & hence remove the Kth element from maxsum i.e, (windowLength + i)

let windowLength = arr.length - k;


/**
 * @param {number[]} cardPoints
 * @param {number} k
 * @return {number}
 */


var maxScore = function (arr, k) {
  let windowLength = arr.length - k;
  let windowSum = 0;
  let maxSum = 0;

  for (let i = windowLength; i < arr.length; i++) {
    windowSum = windowSum + arr[i];
  }
  maxSum = windowSum;

  for (let i = 0; i < arr.length - windowLength; i++) {
    windowSum = windowSum - arr[windowLength + i] + arr[i];
    maxSum = Math.max(maxSum, windowSum);
  }
  return maxSum;
};

console.log(maxScore([1, 79, 80, 1, 1, 1, 200, 1], 3));
console.log(maxScore([1, 2, 3, 4, 5, 6, 1], 3));
console.log(maxScore([2, 2, 2], 2));
console.log(maxScore([9, 7, 7, 9, 7, 7, 9], 7));

Enter fullscreen mode Exit fullscreen mode

Top comments (0)