DEV Community

Abhi Raj
Abhi Raj

Posted on

learn sliding window algorithm easily in Hindi | maximum sum subarray of size k with sliding window


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);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)