in this video i have explained how to learn sliding window algorithm easily in Hindi
for those of you who don't want to watch video here is the code:
//find the maximum sum of size ‘k’ consecutive elements in the array.
let a = [4, 2, 3, 5, 1, 2];
//       0  1  2  3  4  5
let n = a.length; // 6
let k = 3;
let maxSum = -Infinity;
let windowStart = 0;
let windowSum = 0;
for (let windowEnd = 0; windowEnd < n; windowEnd++) {
  windowSum = windowSum + a[windowEnd];
  if (windowEnd - windowStart + 1 == k) {
    maxSum = Math.max(maxSum, windowSum);
    windowSum = windowSum - a[windowStart];
    windowStart++;
  }
}
console.log(maxSum);
    
Top comments (0)