1690. Length-Weighted Peaks

Medium3.5 points estimatedMonotonic StackMathsCombinatoricsArray

A weather station logs one reading per hour in nums. For any contiguous window of hours, define its weight as the highest reading in the window multiplied by the number of hours the window covers. Return the sum of the weights of all windows, modulo 1000000007.

Give every window to the leftmost position that holds its maximum. If position i can reach L choices on its left (counting itself) and R choices on its right (counting itself) before a larger-or-equal element on the left, or a strictly larger one on the right, the windows it owns have total length L*R*(L+R)/2. Computing L and R with a monotonic stack gives O(n) time and O(n) space. Beware that the intermediate products overflow 32-bit integers.

Example 1

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

The subarrays give 1, 2, 3, 2x2, 3x2 and 3x3, which total 25.

Example 2

Input:
nums = [5,5]
Output:
20
Explanation:

The subarrays [5], [5] and [5, 5] contribute 5, 5 and 5x2, a total of 20.

Example 3

Input:
nums = [2]
Output:
2
Explanation:

The only subarray is [2] with maximum 2 and length 1.

Constraints

1 ≤ n ≤ 105; 1 ≤ nums[i] ≤ 109; answer taken mod 109 + 7

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…