It usessliding_window It must be having [difficulty:: medium], it takes [time complexity:: O(n)].
- Below is the code I was able to write and [time taken:: 20mins]
Break it down
- Lets say we have to find maximum sum of 3 consecutive elements
Code
function maxSum(arr, arrLen, windowSize) {
let max = 0;
let sum = 0;
for (let i = 0; i < windowSize; i++) {
sum += arr[i];
}
max = sum;
for (let j = windowSize; j < arrLen; j++) {
// move window, first element reduce from sum, last element of window add to sum, if sum greater assign to max
let winFirstEl = arr[j-windowSize];
const winLastEl = arr[j];
sum += winLastEl - winFirstEl;
if (sum > max) {
max = sum;
}
}
return max;
}
// Driver code
let arr = [1, 4, 2, 10, 2, 3, 1, 0, 20];
let k = 4;
let n = arr.length;
console.log(maxSum(arr, n, k));