1. Brute Force

class Solution:
    def largestSubarray(self, nums: List[int], k: int) -> List[int]:
        res = nums[:k]
        for i in range(1, len(nums) - k + 1):
            window = nums[i:i + k]
            if window > res:
                res = window
        return res

Time & Space Complexity

  • Time complexity: O((n−k+1)∗k)O((n - k + 1) * k)
  • Space complexity: O(k)O(k)

Where nn is the length of the array numsnums and kk is the length of the subarray.


2. Greedy

class Solution:
    def largestSubarray(self, nums: List[int], k: int) -> List[int]:
        best = 0
        for i in range(1, len(nums) - k + 1):
            if nums[i] > nums[best]:
                best = i
        return nums[best:best + k]

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1) extra space.

Where nn is the length of the array numsnums.


3. Greedy (Handling Duplicates)

class Solution:
    def largestSubarray(self, nums: List[int], k: int) -> List[int]:
        best = 0
        for i in range(1, len(nums) - k + 1):
            d = 0
            while d < k and nums[i + d] == nums[best + d]:
                d += 1
            if d < k and nums[i + d] > nums[best + d]:
                best = i
        return nums[best:best + k]

Time & Space Complexity

  • Time complexity: O(n∗k)O(n * k) in the worst case, O(n)O(n) when all values are distinct.
  • Space complexity: O(1)O(1) extra space.

Where nn is the length of the array numsnums and kk is the length of the subarray.