Skip to content

1708. Largest Subarray Length K 👎

  • Time: $O(n)$
  • Space: $O(n)$
1
2
3
4
5
6
7
class Solution {
 public:
  vector<int> largestSubarray(vector<int>& nums, int k) {
    const auto it = max_element(nums.begin(), nums.end() - k + 1);
    return std::vector<int>(it, it + k);
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public int[] largestSubarray(int[] nums, int k) {
    int maxIndex = 0;
    for (int i = 1; i <= nums.length - k; ++i)
      if (nums[i] > nums[maxIndex])
        maxIndex = i;
    return Arrays.copyOfRange(nums, maxIndex, maxIndex + k);
  }
}
1
2
3
4
5
class Solution:
  def largestSubarray(self, nums: list[int], k: int) -> list[int]:
    mx = max(nums[:len(nums) - k + 1])
    i = nums.index(mx)
    return nums[i:i + k]