An arcade machine shows a "score to beat" banner: the k-th highest score recorded so far. Scores keep arriving one at a time, and after each one the banner must be refreshed.
Build a class ScoreBoard:
ScoreBoard(k, scores)starts with the fixed numberkand a list of scores already recorded (possibly empty).add(score)records a new score and returns thek-th highest of all scores recorded so far, counting repeats separately (so in[7, 7, 3]the 2nd highest is7).
board = ScoreBoard(3, [40, 10, 25, 55])
board.add(30) # 30 (55, 40, 30, 25, 10)
board.add(5) # 30
board.add(60) # 40 (60, 55, 40, ...)
board.add(40) # 40 (60, 55, 40, 40, ...)
board.add(70) # 55
solo = ScoreBoard(1, [])
solo.add(-4) # -4
solo.add(-9) # -4
Constraints:
1 <= k <= 10^5and0 <= len(scores) <= 10^5; scores are in[-10^9, 10^9].- Up to
10^5calls toadd. Wheneveraddis called, at leastkscores exist once the new one is counted. - Sorting all scores on every call is far too slow at this size. Aim for O(log k) per
addafter an O(n log k) (or better) setup.
Show hint
Scores below the current banner can never matter again. Keep only the k best, arranged so the smallest of them is instantly available and can be swapped out cheaply.