1713. Wide Window Minimum Total

A weather station records one temperature reading per hour, so nums[i] is the reading of hour i. A report may cover any run of consecutive hours as long as it spans at least k hours, and the "low" of a report is the smallest reading inside it. Return the sum of the lows over every possible report, that is, over all subarrays of nums whose length is at least k, as a 64-bit integer (it is below 2^53). There are 1 to 100000 readings, each between 0 and 100000, and 1 <= k <= n. Aim for O(n) time and O(n) space: let each index own the subarrays where it is the leftmost minimum, count the admissible left and right extensions in constant time with a triangle subtraction, and add nums[i] times that count.

Example 1

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

The subarrays [3,1], [1,2] and [3,1,2] all have minimum 1, so the total is 3.

Example 2

Input:
nums = [5], k = 1
Output:
5
Explanation:

Only the single reading exists and its low is 5.

Example 3

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

The reports [2,4,3], [4,3,1] and [2,4,3,1] have lows 2, 1 and 1, totalling 4.

Constraints

1 ≤ k ≤ n ≤ 105

0 ≤ nums[i] ≤ 105

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…