Consider an array A of integers of length n. The k-max subarray sum asks us to find up to \$k \leq 3\$ (contiguous) non overlapping subarrays of A with maximum sum. If A is all negative then this sum will be 0. If A = [-1, 2, -1, 2, -1, 2, 2] and k=2 for example, then the two subarrays could be [2, -1, 2] and [2, 2] with total sum 7.
Task
Output a list of index pairs representing the subarrays that are being used to form the final k-max subarray sum. In the example just shown I would like the output to be [(1, 3), (5, 6]]
to show the subarrays as index pairs in the original array.
Examples:
[8, -5, 1, 0, -6, -7, 2, 4, 0, -1, -1, 6, -2, 5, 7, 8]
k = 1 should give [(6, 15)].
k = 2 should give [(0,0), (6, 15)].
k = 3 should give [(0,0), (6,7), (11, 15)]
[-3, 0, 2, 2, 0, 0, -1, 1, 3, -2]
k = 1 should give [(1, 8)]
k = 2 should give [(1, 3), (7, 8)]
k = 3 should give [(1, 3), (7, 8)]
[2, 5, -5, 5, 2, -6, 3, -4, 3, -3, -1, 1, 5, -2, 2, -5]
k = 1 should give [(0, 4)]
k = 2 should give [(0, 4), (11, 12)]
k = 3 should give [(0, 1), (3, 4), (11, 12)]
[2, -12, -3, 5, -14, -4, 13, 3, 13, -6, -10, -7, -2, -1, 0, -2, 10, -9, -4, 15]
k = 1 should give [(6, 8]]
k = 2 should give [(6, 8), (19, 19)]
k = 3 should give [(6, 8), (16, 16), (19, 19)]
[1, 1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1]
k = 1 should give [(8, 16)]
k = 2 should give [(0, 1), (8, 16)]
k = 3 should give [(0, 1), (3, 3), (8, 16)]
You can 1-index if you prefer. You may also output a flat list of indices rather than a list of pairs.
Input
An array of integers and a positive integer k.
k will be at most 3.
Restriction
Your code should run in linear time. That is, its running time must be \$O(n)\$.