410. Split Array Largest Sum
Asked at 22Google58Amazon54Bloomberg53Microsoft46Meta46Apple22UKG72Pinterest70Snap55Uber52Baidu100Zeta82Tekion74Okta71Nutanix60PhonePe53Samsung53Infosys50Deloitte50DE Shaw47Flipkart43Goldman Sachs21
Problem
Split nums (non-negative) into k non-empty contiguous parts so that the largest part sum is as small as possible. Return that minimal largest sum.
Example: nums = [7,2,5,10,8], k = 2 → 18 ([7,2,5] and [10,8])
Constraints: n ≤ 1000; k ≤ min(50, n).
Same as shipping packages: minimize the largest piece sum when splitting into k parts. Binary search the answer; greedily count parts needed.
Complexity: O(n log sum).
class Solution:
def splitArray(self, nums: List[int], k: int) -> int:
def parts(cap):
cnt, s = 1, 0
for x in nums:
if s + x > cap:
cnt, s = cnt + 1, 0
s += x
return cnt
lo, hi = max(nums), sum(nums)
while lo < hi:
mid = (lo + hi) // 2
if parts(mid) <= k:
hi = mid
else:
lo = mid + 1
return lo
assert Solution().splitArray([7, 2, 5, 10, 8], 2) == 18
assert Solution().splitArray([1, 2, 3, 4, 5], 2) == 9
class Solution {
public int splitArray(int[] nums, int k) {
long lo = 0, hi = 0;
for (int x : nums) { lo = Math.max(lo, x); hi += x; }
while (lo < hi) {
long mid = (lo + hi) / 2;
int cnt = 1;
long s = 0;
for (int x : nums) {
if (s + x > mid) { cnt++; s = 0; }
s += x;
}
if (cnt <= k) hi = mid; else lo = mid + 1;
}
return (int) lo;
}
}
func splitArray(nums []int, k int) int {
parts := func(limit int) int { // pieces needed if no piece may exceed limit
cnt, s := 1, 0
for _, x := range nums {
if s+x > limit {
cnt, s = cnt+1, 0
}
s += x
}
return cnt
}
lo, hi := 0, 0
for _, x := range nums {
lo = max(lo, x)
hi += x
}
for lo < hi {
mid := lo + (hi-lo)/2
if parts(mid) <= k {
hi = mid
} else {
lo = mid + 1
}
}
return lo
}