1319. Raise to Peak Window

A greenhouse holds a row of plants whose heights are stored in the array nums. A gardener picks a contiguous group of plants and raises every plant in the group up to the height of the tallest plant of that group. Lifting a plant by one unit of height costs one unit of budget, and the group's cost is the sum of all these lifts.

Return the largest number of plants in a contiguous group whose total raising cost is at most budget. A group of one plant costs nothing, so the answer is at least 1. The budget can be as large as 10^15, so use 64-bit arithmetic. Aim for O(n) time and O(n) extra space with two pointers and a monotonic deque for the group's tallest plant.

Example 1

Input:
nums = [3,1,2,5,4], budget = 3
Output:
3
Explanation:

Raising (3, 1, 2) to height 3 costs 0 + 2 + 1 = 3, and every group of 4 plants costs at least 8, so the longest group has 3 plants.

Example 2

Input:
nums = [4,4,4], budget = 0
Output:
3
Explanation:

The plants already share one height, so the whole row costs nothing.

Example 3

Input:
nums = [1,9], budget = 5
Output:
1
Explanation:

Raising the 1 to 9 costs 8, which is over the budget of 5, so only single plants fit.

Constraints

  • 1 ≤ n ≤ 105, where n is the length of nums
  • 1 ≤ nums[i] ≤ 105
  • 0 ≤ budget ≤ 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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(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…