You are given n queues, each represented as a list of integers whose first element is the front of the queue. You can only remove elements from the front of a queue, so from each queue you take some number of its leading elements, in order. You may take zero elements from a queue, or all of them.
Select exactly k elements in total across all queues so that their sum is as large as possible, and return that maximum sum.
Function Signature
def max_sum_from_queue_fronts(queues: list[list[int]], k: int) -> int:
Rules
-
queues[i][0]
is the front of queue
i
. Taking
t
elements from queue
i
means taking
queues[i][0]
through
queues[i][t - 1]
.
-
The counts taken from the individual queues must add up to exactly
k
.
-
Values can be negative, so the maximum sum can be negative. Because
k
never exceeds the total number of elements, a valid selection always exists.
Constraints
-
1 <= n <= 50
-
1 <= len(queues[i]) <= 200
-
1 <= k <=
the total number of elements across all queues
-
-10^4 <= queues[i][j] <= 10^4
Examples
Input: queues = [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [10, 1, 1, 1, 1]], k = 5
Output: 24
Take nothing from queue 0, four elements from queue 1 (5 + 4 + 3 + 2 = 14) and one from queue 2 (10), for 24. Every other split is lower; for example, two from queue 1 and three from queue 2 give 9 + 12 = 21.
Input: queues = [[3, 7, 2], [1, 9, 5]], k = 3
Output: 15
The four possible splits give 3 + 7 + 2 = 12 (all from queue 0), 3 + 7 + 1 = 11, 3 + 1 + 9 = 13, and 1 + 9 + 5 = 15 (all from queue 1). The largest is 15.
Input: queues = [[-1, 10], [2, 1]], k = 2
Output: 9
Taking both elements of queue 0 gives -1 + 10 = 9. Taking both from queue 1 gives 3, and one from each queue gives -1 + 2 = 1.