1516. Most Frequent After Shifts

A thermostat network records one reading in nums[i] for each of its n sensors. A technician may recalibrate the sensors: one move raises or lowers a single sensor's reading by exactly 1, and the technician has at most k moves in total. Readings may be moved to any integer value, and the same sensor may be moved several times.

Return the largest number of sensors that can show one common reading after at most k moves. Hint: sort the readings first. A group of sensors that is adjacent in sorted order is cheapest to equalise by moving all of them to the group's median, and its cost never decreases when the group grows. So use prefix sums to price a window in constant time and slide or binary search the window size. The result is at least 1. Aim for O(n log n) time and O(n) extra space.

Example 1

Input:
nums = [4,9,6,3], k = 5
Output:
3
Explanation:

Sorted readings 3,4,6,9: moving 3 and 4 to 6 costs 3 + 2 = 5, so three sensors can match.

Example 2

Input:
nums = [10,10,10], k = 0
Output:
3
Explanation:

All three readings already agree and no moves are needed.

Example 3

Input:
nums = [1,100], k = 10
Output:
1
Explanation:

The two readings are 99 apart, so with 10 moves only a single sensor can be kept.

Constraints

1 ≤ n ≤ 105

1 ≤ nums[i] ≤ 109

0 ≤ k ≤ 1014

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…