Categories
interview

Largest Subarray Length K

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var largestSubarray = function(arr, k) {
  let max = arr[0];
  let maxIndex = 0;
  for (let i = 0; i <= arr.length - k; i++) {
    if (arr[i] > max) {
      max = arr[i];
      maxIndex = i;
    }
  }

  return arr.slice(maxIndex, maxIndex + k);
};

console.log(largestSubarray([1, 4, 5, 2, 3], 4));
// [4, 5, 2, 3]

Demo