Largest Subarray Length K — LeetCode 1708 Python Solution
- Problem
- #1708
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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 index 1, 3 > 2.
Example
- 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].
Python solution
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]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1708. Largest Subarray Length K is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1708. Largest Subarray Length K?
- LeetCode 1708. Largest Subarray Length K is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1708. Largest Subarray Length K?
- The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 1708. Largest Subarray Length K?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1708. Largest Subarray Length K cover?
- LeetCode 1708. Largest Subarray Length K is tagged Greedy and Array on LeetCode.
- Is LeetCode 1708. Largest Subarray Length K a premium problem?
- Yes. LeetCode 1708. Largest Subarray Length K is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.