#C12796. Contiguous Sublists Under Threshold
Contiguous Sublists Under Threshold
Contiguous Sublists Under Threshold
You are given a list of integers and an integer threshold. Your task is to divide the list into contiguous sublists such that the sum of the elements in each sublist does not exceed the threshold. Moreover, each sublist should be as long as possible while satisfying the constraint:
\(\sum_{x \in \text{sublist}} x \leq \text{threshold}\)
If adding the next number in the list would cause the current sublist's sum to exceed the threshold, then end the current sublist and, if possible, start a new one. If a single number is greater than the threshold, skip it (do not include it in any sublist).
For example, given the list [1, 2, 3, 4]
with a threshold of 5
, the answer is [[1, 2], [3], [4]]
because:
1 + 2 = 3
(<= 5) but adding3
would exceed 5.- Then,
3
alone is valid and4
forms its own sublist.
inputFormat
The input is given via standard input (stdin
) in the following format:
- The first line contains a single integer
n
representing the number of elements in the list. - The second line contains
n
space-separated integers. - The third line contains the integer
threshold
.
Example:
4 1 2 3 4 5
outputFormat
Output the contiguous sublists as a JSON array of arrays to standard output (stdout
). Each sublist should appear in the order they are found. For the given example, the output should be:
[[1,2],[3],[4]]## sample
4
1 2 3 4
5
[[1,2],[3],[4]]