Given an integer array nums and an integer k, remove every value except the k largest elements. The relative order of the retained elements must be the same as in the original array.
If there are ties at the cutoff value, keep the earliest tied elements until exactly k elements have been retained.
Examples
01 · Example 1
nums = [5,1,3,5,2] k = 3 return = [5,3,5]
The three largest elements are 5, 5, and 3. They are returned in their original order.
02 · Example 2
nums = [4,4,4,2] k = 2 return = [4,4]
When equal values cross the cutoff, keep the earliest occurrences needed to return exactly k elements.
Constraints
Assume 0 <= k <= nums.length. The return value should contain exactly k elements.
More Microsoft problems
- Rank Open BusinessesPHONE SCREEN · Seen May 2026
- In-Memory SQL with CSV InitializationONSITE INTERVIEW · Seen May 2026
- Order Records by Matching Start and EndONSITE INTERVIEW · Seen May 2026
- Recover Corrupted Master PageONSITE INTERVIEW · Seen Feb 2026
- Distinct Number Line MovesOA · Seen Oct 2025
- Get Minimum TimeSeen Jun 2025
- Count Subarrays with Bitwise OR PresentSeen Jun 2025
- Get Max Or SumSeen Jun 2025
public int[] retainTopKValues(int[] nums, int k) {
// write your code here
}
nums[5,1,3,5,2]
k3
expected[5,3,5]
sign in to submit