Given an array 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.
Note:
Given m satisfies the following constraint: 1 ≤ m ≤ length(nums) ≤ 14,000.
Examples:
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. 分析:暴力解法 虽然要把数组分成几份,但是因为数组里的元素是连续的,所以,我们可以把前面部分当成第一份,然后找出后边部分分出 m - 1次时最大的和。所以递归方法可解。但是,很明显,cost太高了。
public class Solution {
//brute-force approach
public int splitArray(int[] nums, int m) {
long[] sums = new long[nums.length];
sums[] = nums[]; for (int i = ; i < sums.length; i++) {
sums[i] = sums[i - ] + nums[i];
} return (int) helper(nums, sums, , sums.length - , m);
} public long helper(int[] nums, long[] sums, int start, int end, int k) {
if (k <= )
return Integer.MAX_VALUE;
if (k == ) {
if (start == ) {
return sums[end];
} else {
return sums[end] - sums[start - ];
}
}
long min = Long.MAX_VALUE; for (int i = start; i <= end; i++) { long leftSum;
if (start == ) {
leftSum = sums[i];
} else {
leftSum = sums[i] - sums[start - ];
} min = Math.min(min, Math.max(leftSum, helper(nums, sums, i + , end, k - )));
}
return min;
}
}
第二种方法:
首先找出数组的最大值max和所有值的和sum。然后那个最小值一定是在max和sum之间。 所以可以利用binary search来寻找。
reference: https://discuss.leetcode.com/topic/61315/java-easy-binary-search-solution-8ms
public class Solution {
public int splitArray(int[] nums, int m) {
long sum = ;
int max = ;
for (int num : nums) {
max = Math.max(max, num);
sum += num;
}
return (int) binary(nums, m, sum, max);
} private long binary(int[] nums, int m, long high, long low) {
long mid = ;
while (low <= high) {
mid = (high + low) / ;
if (valid(nums, m, mid)) {
high = mid - ;
} else {
low = mid + ;
}
}
return low;
} private boolean valid(int[] nums, int m, long max) {
int cur = , count = ;
for (int num : nums) {
cur += num;
if (cur > max) {
cur = num;
count++;
if (count > m) {
return false;
}
}
}
return true;
}
}