您的位置:首页 > 其它

[LeetCode]410. Split Array Largest Sum

2017-01-15 21:38 441 查看
https://leetcode.com/problems/split-array-largest-sum/

所求子数组和一定是在sum和max之间。用二分查找,找到这个值target。二分的判断条件为valid函数,valid里面遍历整个nums,每当当前子数组的和大于target,则count(小于等于target的子数组数目)加一,如果count > m则当前target非valid。

public class Solution {
public int splitArray(int[] nums, int m) {
int sum = 0;
int max = 0;
for (int num : nums) {
sum += num;
max = Math.max(max, num);
}
if (m == 1) {
return sum;
}
int l = max;
int r = sum;
while (l <= r) {
int mid = l + (r - l) / 2;
if (valid(mid, nums, m)) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return l;
}
private boolean valid(int target, int[] nums, int m) {
int count = 1;
int total = 0;
for (int num : nums) {
total += num;
if (total > target) {
total = num;
count++;
if (count > m) {
return false;
}
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: