JS | Array | Maximum sum of ‘k’ consecutive | Sliding window technique | O(n)

// Returns maximum sum in a subarray of size k.function maxSum( arr, n, k){   // Initialize result
let max_sum = Number.MIN_VALUE;
for (let i = 0; i < n - k + 1; i++) {
let current_sum = 0;
for (let j = 0; j < k; j++)
current_sum = current_sum + arr[i + j];
max_sum = Math.max(current_sum, max_sum); } return max_sum;}
function maxSum(arr, n, k) {   let max = 0;
let sum = 0;
// find initial sum of first k elements for (let i = 0; i < k; i++) { sum += arr[i]; max = sum; } // iterate the array once and increment the right edge for (let i = k; i < n; i++) { sum += arr[i] - arr[i - k]; // compare if sum is more than max, if yes then replace max with new sum value if (sum > max) { max = sum; } }return max;}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store