ORIGINAL CODING QUESTION
Readings nearest a calibration point
A sensor log holds n readings, possibly repeated. Rank readings by their distance |reading - x| from the calibration point x; among equal distances the smaller reading ranks first. Keep the k best-ranked readings (repeated readings are separate entries) and return their sum.
Original exercise · medium. Editorial role relevance does not imply a company has asked this question.
Input and output
n, then n readings, then x and k.
Constraints
1 ≤ k ≤ n ≤ 200; -1000 ≤ reading, x ≤ 1000.
Example 1
Input
5 1 4 6 9 10 5 2
Output
10
Readings 4 and 6 are each 1 away from 5, totalling 10.
Example 2
Input
4 3 7 3 7 5 3
Output
13
All are 2 away; the tie rule picks 3, 3 and then 7, totalling 13.
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
Define a single comparison that uses distance first and the reading second.
Hint 2
A max-heap of size k holds the best k seen so far, with the worst on top.
Hint 3
Evict the top whenever the heap grows past k.
Practice this question
Save your work privately, explain decisions and return to your revision queue.
Open practice workspaceBrowse the question library →