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));    }}
原创粉丝点击