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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,593评论 0 23
  • “说 ‘食不语’,为何?”“吃东西快吧。”“哼,该你时都快。”“看分什么,如癫、忍、谦、嗜者,需多嚼。”“怎解?”...
    dic阅读 1,868评论 0 2
  • 今早的大课间,王佳琪出现的很准时,拿着应该是四天前的作业,来我的房间继续我给她的“小灶” 。 我...
    夕_颜阅读 1,796评论 2 1
  • 没有写过什么日记,没有写过什么随笔。 也从来没有编辑过一些文字,虽然我是文科的(小时候的作文不能算,那是应付考试)...
    向日葵般的丫子阅读 1,481评论 0 0
  • 愿我来世,得菩提时,心似琉璃 -------药师琉璃光如来本愿功德经 每到暮色四合...
    Lucky_leaf阅读 1,693评论 0 1

友情链接更多精彩内容