15. Split Array Largest Sum

Link to the problem

Description

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)

Example

Input: nums = [7,2,5,10,8], m = 2, Output: 18

Idea

Binary search for the minimum S, such that it's possible to group consecutive subarrays, each of sum at most S. To check feasibility for a given S, just greedily group consecutive elements whose sum do not exceed S.

Solution

class Solution {
private:
    int nSplit(vector<int> &nums, int thres) {
        int numSplit = 1;
        int curSum = 0;
        for (auto it = nums.begin(); it != nums.end(); it++) {
            if (curSum + *it > thres) {
                numSplit++;
                curSum = *it;
            } else {
                curSum += *it;
            }
        }
        return numSplit;
    }
public:
    int splitArray(vector<int>& nums, int m) {
        int lo = 0;
        int hi = 0;
        for (auto it = nums.begin(); it != nums.end(); it++) {
            hi += *it;
            lo = max(lo, *it);
        }
        // binary search for the minimum feasible largest sum
        while (lo < hi) {
            int mi = lo + (hi - lo) / 2;
            if (nSplit(nums, mi) <= m) {
                hi = mi;
            } else {
                lo = mi + 1;
            }
        }
        return lo;
    }
};

27 / 27 test cases passed.
Runtime: 3 ms

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,055評論 0 23
  • “說 ‘食不語’,為何?”“吃東西快吧。”“哼,該你時都快?!薄翱捶质裁矗绨d、忍、謙、嗜者,需多嚼?!薄霸踅?”...
    dic閱讀 296評論 0 2
  • 今早的大課間,王佳琪出現(xiàn)的很準時,拿著應(yīng)該是四天前的作業(yè),來我的房間繼續(xù)我給她的“小灶” 。 我...
    夕_顏閱讀 305評論 2 1
  • 沒有寫過什么日記,沒有寫過什么隨筆。 也從來沒有編輯過一些文字,雖然我是文科的(小時候的作文不能算,那是應(yīng)付考試)...
    向日葵般的丫子閱讀 217評論 0 0
  • 愿我來世,得菩提時,心似琉璃 -------藥師琉璃光如來本愿功德經(jīng) 每到暮色四合...
    Lucky_leaf閱讀 265評論 0 1

友情鏈接更多精彩內(nèi)容