1321. Calm and Heavy Stretches

A warehouse records the weights of n crates in order, all positive, in the array nums. A contiguous run of crates is acceptable when two things hold: its heaviest crate minus its lightest crate is at most limit, and its total weight is at least minSum. Count the acceptable runs and return the count as a 64-bit integer. For each right end, the starts meeting the spread condition begin at a pointer found with two monotonic deques, the starts meeting the weight condition end at a second pointer found with prefix sums, and the answer adds the size of the overlap. Target O(n) time and O(n) space.

Example 1

Input:
nums = [2,5,3,4], limit = 2, minSum = 7
Output:
3
Explanation:

The runs [5, 3], [3, 4] and [5, 3, 4] have spread at most 2 and weight at least 7, so the count is 3.

Example 2

Input:
nums = [4,4,4], limit = 0, minSum = 8
Output:
3
Explanation:

With limit 0 all three crates are equal, and the runs [4, 4] (twice) and [4, 4, 4] reach weight 8, giving 3.

Example 3

Input:
nums = [1,9], limit = 8, minSum = 5
Output:
2
Explanation:

The run [1, 9] has spread 8 and weight 10, [9] has weight 9, and [1] weighs only 1, so the count is 2.

Constraints

1 ≤ n ≤ 2*105

1 ≤ nums[i] ≤ 109

0 ≤ limit ≤ 109

1 ≤ minSum ≤ 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)
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…