[LeetCode] Largest Subarray Length K

1708. Largest Subarray Length K

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
vector<int> largestSubarray(vector<int>& nums, int k) {
int best = 0;
for(int i = 1; i < nums.size() - k + 1; i++) {
if(nums[best] < nums[i]) best = i;
}
vector<int> res;
for(int i = 0; i < k; i++) {
res.push_back(nums[best+i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/16/PS/LeetCode/largest-subarray-length-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.