Categories
interview

Maximum Subarray of size K

// Uses sliding window technique. Runtime Complexity 0(n).
const maxSubarraySizeK = (arr, k) => {
  if (arr.length < k) {
    return [];
  }
  let sum = 0;
  let s = 0;
  let maxSum = Number.MIN_VALUE;
  for (let i = 0; i < arr.length; i++) {
    if (i < k) {
      sum += arr[i];
      maxSum = sum;
    } else {
      sum += arr[i] - arr[i - k];
      if (sum > maxSum) {
        maxSum = sum;
        s = i - k + 1;
      }
    }
  }
  return arr.slice(s, s + k);
};

console.log(maxSubarraySizeK([1, 4, 2, 10, 2, 3, 1, 0, 20], 4));
// [3, 1, 0, 20]  - 24

Demo