1694. Odd Stretch Spread

Medium3.5 points estimatedMonotonic StackCombinatoricsMathsArray

A sensor logs nums[i] readings in a row. The spread of a stretch of consecutive readings is its largest value minus its smallest value. Only stretches with an odd number of readings are trusted by the lab. Return, as a long, the sum of the spreads of all odd-length subarrays of nums (a single reading is a stretch of length 1 with spread 0). Two stretches are different when their start or end positions differ. A direct scan of every subarray is O(n^2); the intended solution counts, for each position, the odd-length stretches where it is the maximum (and separately the minimum) using monotonic stacks, in O(n) time and O(n) space. The answer fits comfortably below 2^53.

Example 1

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

Singles contribute 0 and the only other odd-length subarray is the whole array, whose spread is 3 - 1 = 2.

Example 2

Input:
nums = [5]
Output:
0
Explanation:

One element: its spread is 0.

Example 3

Input:
nums = [2,9,4,7,1]
Output:
26
Explanation:

The three windows of length 3 have spreads 7, 5 and 6, the whole array has spread 8, and singles give 0: 7 + 5 + 6 + 8 = 26.

Constraints

1 ≤ nums.length ≤ 105

0 ≤ nums[i] ≤ 106

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)
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…