leetcode題解-410. Split Array Largest Sum

題目:

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分,然後最小化各子數組的和的最大值。其實看到這個題目,我完全想不到他跟binary-search有什麼關係。畢竟它的原理跟切分數組沒有什麼聯繫。然後就去看了別人的答案,才恍然大悟。原來binary-search還可以這麼用==因爲題目是要切分數組,然後最小化數組的和,所以呢,我們可以對數組的和進行binary-search。可以想到,數組和的最小值是最大元素的值,最大值是所有元素的和(注意溢出),然後我們對該區間進行二叉搜索,直到找到合適的結果。那麼如何判斷一個值是否滿足呢,我們可以定義一個函數來判斷數組是否可以滿足該值。代碼入下:

    public int splitArray(int[] nums, int m) {
        //取出最大值和最小值
        int max = 0; long sum = 0;
        for (int num : nums) {
            max = Math.max(num, max);
            sum += num;
        }
        if (m == 1) return (int)sum;
        //binary search
        long l = max; long r = sum;
        while (l <= r) {
            long mid = (l + r)/ 2;
            //調用valid函數判斷當前值是否滿足條件
            if (valid(mid, nums, m)) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return (int)l;
    }
    public boolean valid(long target, int[] nums, int m) {
        int count = 1;
        long total = 0;
        //對數組進行分段求和,每當和大於target時,就重新求和,如果數組總數大於m,則說明target太小,需要增加,返回false
        for(int num : nums) {
            total += num;
            if (total > target) {
                total = num;
                count++;
                if (count > m) {
                    return false;
                }
            }
        }
        return true;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章