This page explains Java solution to problem Split Array Largest Sum
using Binary Search
algorithm.
Given an array nums
which consists of non-negative integers and an integer m
, you can split the array into m
non-empty continuous subarrays.
Write an algorithm to minimize the largest sum among these m
subarrays.
Example 2:Input: nums = [7,2,5,10,8], m = 2
Output: 18
Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.
Example 3:Input: nums = [1,2,3,4,5], m = 2
Output: 9
Input: nums = [1,4,4], m = 3
Output: 4
package com.vc.hard;
class SplitArrayLargestSum {
public int splitArray(int[] nums, int m) {
if(nums == null || nums.length == 0) return 0;
int lo = Integer.MIN_VALUE;
int hi = 0;
for(int i = 0; i < nums.length; i++) {
lo = Math.max(lo, nums[i]);
hi += nums[i];
}
if(m == 1) return hi;
while(lo < hi) {
int mid = lo + (hi - lo) / 2;
if(isMorePartitions(nums, mid, m)) lo = mid + 1;
else hi = mid;
}
return lo;
}
private boolean isMorePartitions(int[] nums, int sum, int expectedPartitions) {
int total = 0;
int partitions = 1;
for(int i = 0; i < nums.length; i++) {
total += nums[i];
if(total > sum) {
total = nums[i];
partitions++;
if(partitions > expectedPartitions) return true;
}
}
return false;
}
}
O(N * log(HI - LO)) Where
N is total number of elements in an input array
Lo is max element in an input array
HI is sum of elements in an input array
O(1)