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

Calculate the maximum sum of **‘k’** consecutive elements in the array.

*Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}, k = 4 Output : 39We get maximum sum by adding subarray {4, 2, 10, 23} of size 4.*

**Brute Force Approach — **O(n*k) solution

// Returns maximum sum in a subarray of size k.functionmaxSum( 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); }returnmax_sum;}

## Sliding Window Approach — O(n)

functionmaxSum(arr, n, k) { let max = 0;

let sum = 0; // find initial sum of first k elementsfor(let i = 0; i < k; i++) { sum += arr[i]; max = sum; } // iterate the array once and increment the right edgefor(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 valueif(sum > max) { max = sum; } }returnmax;}

Reference -

- https://leetcode.com/problems/maximum-subarray/
- https://www.geeksforgeeks.org/window-sliding-technique/
- More Sliding Window Technique Questions

If you want to learn more on data structure, book a session with me on www.startlearncoding.com

- Follow me for more coding interviews.
- This problem is very popular in coding interviews.
- Keep learning, keep growing!
- Don’t forget to follow me for more such articles, and subscribe to our newsletter.
- Let’s connect on LinkedIn!. Please read more for more
.*data structure javascript questions*