Partition Array Under Segment Capacity Limit
Greedy & IntervalsAuto-graded · 25 test casesLast updated
Determine the minimum number of contiguous segments needed to split an array such that no segment's total sum exceeds a specified capacity limit.
Given a list of non-negative integers a representing payload sizes and an integer k representing the maximum allowed capacity for a single segment, divide the array into the minimum possible number of contiguous sub-arrays (segments) such that the sum of elements in each segment does not exceed k.
If any individual payload in a is strictly greater than k, it is impossible to form valid segments; return -1.
If the input array a is empty, return 0.
Constraints
- $0 \le \text{len}(a) \le 10^5$
- $0 \le a[i] \le 10^9$ for all $0 \le i < \text{len}(a)$
- $0 \le k \le 10^9$
Examples
Example 1
Input: min_contiguous_segments([1, 2, 3, 4, 5], 5)
Output: 4
Example 2
Input: min_contiguous_segments([2, 2, 2], 4)
Output: 2
Example 3
Input: min_contiguous_segments([7, 2, 1], 7)
Output: 2
Hints
Hint 1
Consider greedily packing as many elements into the current segment as possible before starting a new one.
Hint 2
Check upfront or during traversal if any single item exceeds the capacity k.
Hint 3
Traverse the array once while keeping track of the running sum of the current segment.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks for the minimum number of contiguous segments needed to partition an array a such that the sum of each segment does not exceed capacity k.
This can be solved using a Greedy strategy:
- First, check if any element in
ais greater thank. If so, no valid segment can contain that element, so return-1. - If
ais empty, return0. - Iterate through the array sequentially, accumulating a running total (
current_sum) for the current segment:- If adding the current element
sizetocurrent_sumwould exceedk, we must finalize the current segment, increment our segment count by 1, and start a new segment initialized withsize. - Otherwise, add
sizetocurrent_sum.
- If adding the current element
Because all elements are non-negative, expanding the current segment as far right as possible never hurts future choices. This greedy choice guarantees an optimal partition with the minimum count of segments.
Complexity
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the number of elements in
a. We process each element a constant number of times. - Space Complexity: $\mathcal{O}(1)$ auxiliary space, as only scalar variables are used.
Python 3 Source Code
from typing import List
def min_contiguous_segments(a: List[int], k: int) -> int:
if not a:
return 0
if any(size > k for size in a):
return -1
segments = 1
current_sum = 0
for size in a:
if current_sum + size > k:
segments += 1
current_sum = size
else:
current_sum += size
return segments