visual walkthrough
Frequency of the Most Frequent Element
MediumSort + Variable Window
Sorting plus a window-sum budget check.
The idea
To make several numbers equal using only increments, raise them all to the largest one among them. After sorting, the cheapest numbers to raise are the ones just below the target, so we only look at windows of neighbours.
The cost of a window is (largest × length) − (sum). Keep the window as long as that stays within k.
Complexity
| approach | time | space |
|---|---|---|
| Each target, reach back | O(n²) | O(1) |
| Sort + sliding window | O(n log n) | O(1) |