[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;
}
}
所求子数组和一定是在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;
}
}
相关文章推荐
- Unity中使用扩展方法解决foreach导致的GC
- HTML5-Canvas绘图练习1
- html中 如何获取屏幕参数??
- Python之协同过滤(寻找相近的用户)
- Java——值传递和引用传递
- 玲珑学院 - -1083 - XJT Love Digits
- 第四章 字典:当索引不好用时
- Apache Commons Betwixt
- 大数据采集平台的架构分析
- 文件或目录损坏且无法读取-chkdsk被中止
- 【动态规划】Gym - 101102A - Coins
- Form表单之下拉框
- ZCMU-1309-Vasya and Public Transport
- C语言提高
- 大二用C++写的huffman树
- Java:String和Date、Timestamp之间的转换
- java-面向对象编程-三大特性之继承
- SQL联合查询(内联、左联、右联、全联)
- 160. Intersection of Two Linked Lists
- Swing窗体创建