Split Array Largest Sum
来源:互联网 发布:js数组去重系统方法 编辑:程序博客网 时间:2024/05/21 08:38
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:
If n is the length of array, assume the following constraints are satisfied:
1 ≤ n ≤ 1000
1 ≤ m ≤ min(50, n)
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 个子数组,则证明m值小了,如果不可以分割m组,则证明值大了。
public class Main { private boolean isOk(int[] nums, int m, long num) { long sum = 0, count = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; if (sum > num) { sum = nums[i]; count++; if (count >= m) return true; } } return false; } public int splitArray(int[] nums, int m) { long sum = 0; int max = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; max = Math.max(nums[i], max); } if (m == 1) return (int) sum; long start = max; long end = sum; while (start <= end) { long mid = (start + end) / 2; if (isOk(nums, m, mid)) { start = mid + 1; } else { end = mid - 1; } } return (int) start; } public static void main(String[] args) { System.out.println(new Main().splitArray(new int[] { 7, 2, 5, 10, 8 }, 2)); }}
阅读全文
0 0
- Split Array Largest Sum
- Split Array Largest Sum
- Split Array Largest Sum
- LeetCode: Split Array Largest Sum
- 410. Split Array Largest Sum
- 410. Split Array Largest Sum
- 410. Split Array Largest Sum
- [Leetcode] Split Array Largest Sum
- 410. Split Array Largest Sum
- 410. Split Array Largest Sum
- 410. Split Array Largest Sum
- 410. Split Array Largest Sum
- 410. Split Array Largest Sum
- 【Leetcode】410. Split Array Largest Sum
- leetcode 410 Split Array Largest Sum
- leetcode 410.Split Array Largest Sum
- LeetCode No.410 Split Array Largest Sum
- leetcode-410. Split Array Largest Sum
- Cordova 开发之安卓插件开发(二)
- Java多线程--重入锁的实现原理
- Solrj的增删改查,高亮,及分页
- 实训经历
- H5基础(6)-HTML5本地存储和本地数据库
- Split Array Largest Sum
- 杂谈
- HDU 2016 数据的交换输出
- 三菱V3菱悦智能遥控匹配详细的(两种)方法 配钥匙
- Netty in action—Netty中的ByteBuf
- elasticsearch学习javaAPI:es的增删改查
- 外部中断
- python网络编程(线程)
- 分布式系统事务一致性