#1708
Easy Algorithms Largest subarray length k
Array Greedy
65.8% acceptance
Mar 31, 2026
110
116
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.
[1,4,4,4] < [2,1,1,1], since at index 0, 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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn largest_subarray(nums: Vec<i32>, k: i32) -> Vec<i32> {
let k = k as usize;
let n = nums.len();
let mut best = 0;
for i in 1..=n - k {
if nums[i] > nums[best] {
best = i;
}
}
nums[best..best + k].to_vec()
}
}