1099. Sum of Window Maximums

A power plant logs its output once per minute in nums. For billing, every block of k consecutive minutes is examined and only its peak output counts. There are nums.length - k + 1 such blocks, and consecutive blocks overlap by k - 1 minutes.

Return the sum of the peak output over all blocks of exactly k consecutive readings. Readings can be negative, equal readings are common, and the total can be far larger than a 32-bit integer, so use a 64-bit result. Rescanning each block from scratch is too slow when k is large.

Example 1

Input:
nums = [3,1,4,1,5,9,2,6], k = 3
Output:
40
Explanation:

The six windows of three readings have peaks 4, 4, 5, 9, 9 and 9, which add up to 40.

Example 2

Input:
nums = [-5,-3,-8], k = 2
Output:
-6
Explanation:

The two windows have peaks -3 and -3, so the total is -6; negative readings are fine.

Example 3

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

One reading and one window: the total is just 7.

Constraints

1 ≤ k ≤ nums.length ≤ 2 * 105

-109 ≤ nums[i] ≤ 109

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 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 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…