1317. Lopsided Levelling

A warehouse stores crates with the heights listed in nums. A crew wants to pick as many crates as possible and make all of them exactly the same height. Lifting a crate one unit taller costs up and shaving one unit off a crate costs down, and the crew can spend at most budget in total. Heights may be changed to any integer and crates may be chosen from anywhere in the list.

Return the largest number of crates that can be made equal in height within the budget. A single crate always qualifies at no cost.

After sorting, the best group is always a run of neighbouring crates. For a run, the cheapest common height is one of its own heights and can be located by binary search with prefix sums, and a longer run never costs less than one of its sub-runs, so two pointers can sweep every run. The intended solution runs in O(n log n) time and O(n) space. Costs can exceed 32 bits.

Example 1

Input:
nums = [1,4,2,10]budget = 6up = 1down = 1
Output:
3
Explanation:

The crates 1, 2 and 4 can all be set to 2 by raising the 1 once and shaving the 4 twice, costing 3, and adding the 10 would cost far more than 6, so the answer is 3.

Example 2

Input:
nums = [5,5,5]budget = 0up = 3down = 7
Output:
3
Explanation:

All crates already have the same height, so all 3 qualify at no cost.

Example 3

Input:
nums = [1,3]budget = 3up = 2down = 100
Output:
1
Explanation:

Raising the 1 to 3 costs 2 * 2 = 4, and shaving the 3 to 1 costs 100 * 2 = 200, both over the budget of 3, so only a single crate remains.

Constraints

  • 1 ≤ nums.length ≤ 105

  • 1 ≤ nums[i] ≤ 106

  • 1 ≤ up, down ≤ 100

  • 0 ≤ budget ≤ 1013

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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,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…