Largest Subarray Length K Problem
#1708
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1708.
An array A is larger than some array B if for the first index i where A[i] != B[i], A[i] > B[i].
For example, consider 0-indexing:
[1,3,2,4] > [1,2,2,4], since at index1,3 > 2.[1,4,4,4] < [2,1,1,1], since at index0,1 < 2.
A subarray is a contiguous subsequence of the array.
Given an integer array nums of distinct integers, return the largest subarray of nums of length k.
Example 1:
Input: nums = [1,4,5,2,3], k = 3
Output: [5,2,3]
Explanation: The subarrays of size 3 are: [1,4,5], [4,5,2], and [5,2,3].
Of these, [5,2,3] is the largest.
Example 2:
Input: nums = [1,4,5,2,3], k = 4
Output: [4,5,2,3]
Explanation: The subarrays of size 4 are: [1,4,5,2], and [4,5,2,3].
Of these, [4,5,2,3] is the largest.
Example 3:
Input: nums = [1,4,5,2,3], k = 1
Output: [5]
Constraints:
1 <= k <= nums.length <= 10^51 <= nums[i] <= 10^9- All the integers of
numsare unique.
Follow up: What if the integers in nums are not distinct?
Solution
Approach: Simulation
Because all numbers are distinct, two subarrays of length k already differ at their first element. So the largest subarray is the one that starts at the largest value among the possible starting positions 0 .. n - k. Find that index and return the k elements from there.
Complexity: O(n) time and O(1) extra space, where n is the length of the array.
class Solution:
def largestSubarray(self, nums: List[int], k: int) -> List[int]:
i = nums.index(max(nums[: len(nums) - k + 1]))
return nums[i : i + k]