Maximum Points You Can Obtain from Cards LeetCode solution in JavaScript

1
/**
2
* @param {number[]} cardPoints
3
* @param {number} k
4
* @return {number}
5
*/
6

7
// Obtaining k cards from the beginning or end of the row for the largest sum, meaning leaving the
8
// array with n-k adjacent cards with the min sum
9
// therefore, this transform the problem to finding the minSum of subarray of length n-k
10
// we use slide window to calculate the minSubArraySum
11
var maxScore = function (cardPoints, k) {
12
const n = cardPoints.length,
13
d = n - k; // d is the window length
14
let sum = 0;
15
for (let i = 0; i < d; i++) {
16
sum += cardPoints[i];
17
}
18
let minWindowSum = sum,
19
totalSum = sum;
20
console.log(sum);
21
for (let i = d; i < n; i++) {
22
// the sum of the next window will the the sum of previous window + the next card (the end card of the next window) - the beginning card of the previous window
23
sum += cardPoints[i] - cardPoints[i - d];
24
minWindowSum = Math.min(minWindowSum, sum);
25
totalSum += cardPoints[i];
26
}
27
// the ans will be the sum of all cards - the sum of min subArray
28
return totalSum - minWindowSum;
29
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0