846. Three Best Windows

A solar farm logs hourly energy output in nums. An engineer will schedule three maintenance blocks, each exactly k consecutive hours long and none overlapping another, and wants to measure the total output over the chosen blocks as large as possible.

Return an array of the three starting indices in increasing order that maximise this total. If several choices give the same maximum total, return the lexicographically smallest array of indices (compare the first index, then the second, then the third). If the log is shorter than 3 * k hours, no valid choice exists and the answer is an empty array.

Aim for time O(n) and space O(n).

Example 1

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

The windows starting at 3, 5 and 7 have sums 11, 11 and 12 (total 34) and do not overlap; no other non-overlapping trio reaches 34.

Example 2

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

Every window of length 2 sums to 9, so all valid trios tie and the lexicographically smallest start indices 0, 2, 4 are returned.

Constraints

1 ≤ nums.length ≤ 105

0 ≤ nums[i] ≤ 1000

1 ≤ k ≤ 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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 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…