FastPrepFastPrep
Problem Brief

Retain Top K Values

FULLTIMEPHONE SCREEN
See Microsoft online assessment and hiring insights

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.

1Example 1

Input
nums = [5,1,3,5,2], k = 3
Output
[5,3,5]
Explanation

The three largest elements are 5, 5, and 3. They are returned in their original order.

2Example 2

Input
nums = [4,4,4,2], k = 2
Output
[4,4]
Explanation

When equal values cross the cutoff, keep the earliest occurrences needed to return exactly k elements.

Constraints

Limits and guarantees your solution can rely on.

Assume 0 <= k <= nums.length. The return value should contain exactly k elements.

public int[] retainTopKValues(int[] nums, int k) {
    // write your code here
}
Input

nums

[5,1,3,5,2]

k

3

Output

[5,3,5]

Sign in to submit your solution.