1309. Level the Stretch
A row of storage tanks holds the amounts in nums. In one step a worker may pour out exactly one unit from a tank or add exactly one unit to a tank, and each step touches a single tank. The workers have at most k steps in total and want to make a block of neighbouring tanks all hold the same amount.
Return the length of the longest block of consecutive tanks that can be levelled to one common amount using at most k steps. The common amount may be any integer. A block of one tank needs zero steps, so the answer is at least 1.
Dropping a tank from either end of a block never makes the job more expensive, so a two-pointer sweep is enough to cover all blocks. Aim for O(n log n) time and O(n) space. Step totals can exceed 32 bits.
Example 1
- Input:
- nums = [1,2,6,3], k = 4
- Output:
- 3
- Explanation:
The tanks 2, 6, 3 are levelled to 3 with 1 + 3 + 0 = 4 steps, and all four tanks would need 6 steps, so the answer is 3.
Example 2
- Input:
- nums = [5,5,5], k = 0
- Output:
- 3
- Explanation:
The tanks are already level, so the whole row of 3 qualifies without any step.
Example 3
- Input:
- nums = [1,10], k = 5
- Output:
- 1
- Explanation:
Levelling the two tanks costs 9 steps, which is more than 5, so only a single tank fits.
Constraints
-
1 ≤ nums.length ≤ 5 * 104 -
1 ≤ nums[i] ≤ 109 -
0 ≤ k ≤ 1015
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)