Skip to content

ORIGINAL CODING QUESTION

Running k-th best assessment score

Assessment scores arrive one at a time. After each arrival, if at least k scores have arrived, note the k-th largest score seen so far; repeated scores count as separate entries. Return the sum of all noted values, or 0 if fewer than k scores ever arrive.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

n k, then n scores in arrival order.

Constraints

1 ≤ n ≤ 200; 1 ≤ k ≤ 200; -1000 ≤ score ≤ 1000.

Example 1

Input

5 2 4 1 7 3 8

Output

16

The noted second-best values are 1, 4, 4 and 7, totalling 16.

Example 2

Input

3 4 5 6 7

Output

0

Only three scores arrive, so nothing is ever noted.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Only the k largest scores so far can affect the answer.

Hint 2

Keep those k scores in a min-heap.

Hint 3

When the heap grows past k, drop its smallest; its top is then the k-th largest.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →