KatInterview

Partition Array Under Segment Capacity Limit

Greedy & IntervalsAuto-graded · 25 test cases

Last 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.