← Home

410. Split Array Largest Sum

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
binary searchC++Markdown
410

The trick here is to name the state correctly, then let the implementation follow. For 410. Split Array Largest Sum, the solution in this repository is mainly a binary search solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: binary search, two pointers, sliding window.

The notes already sitting in the source point us in the right direction:

  • binary search
  • https://leetcode.com/problems/split-array-largest-sum/discuss/89817/Clear-Explanation%3A-8ms-Binary-Search-Java

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are isValid, splitArray.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//binary search
02//https://leetcode.com/problems/split-array-largest-sum/discuss/89817/Clear-Explanation%3A-8ms-Binary-Search-Java
03//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Split Array Largest Sum.
04//Memory Usage: 7.1 MB, less than 100.00% of C++ online submissions for Split Array Largest Sum.
05class Solution {
06public:
07    bool isValid(vector<int>& nums, int m, long long maxSubSum){
08        long long subSum = 0;
09        int count = 1; //number of subarrays
10        
11        for(int num : nums){
12            subSum += num;
13            if(subSum > maxSubSum){
14                /*
15                current sub array's sum > maxSubSum,
16                so we need a new split
17                */
18                subSum = num;
19                count++;
20                if(count > m){
21                    return false;
22                }
23            }
24        }
25        
26        return true;
27    };
28    
29    int splitArray(vector<int>& nums, int m) {
30        //the max value and sum of the array
31        long long _max = 0, _sum = 0;
32        
33        for(long long num : nums){
34            _max = max(_max, num);
35            _sum += num;
36        }
37        
38        /*
39        suppose nums's length is n,
40        if we can have n subarrays, the max value of sum of each subarray is _max
41        if we can only have 1 subarray, the sum of this subarray is _sum
42        */
43        long long left = _max, right = _sum, mid;
44        
45        //[left, right]: inclusive
46        while(left <= right){
47            mid = left + (right-left)/2;
48            // cout << left << ", " << mid << ", " << right << endl;
49            if(isValid(nums, m, mid)){
50                //mid is already searched, so next time we don't search mid
51                //[left, mid) -> [left, mid-1]
52                right = mid - 1;
53            }else{
54                //(mid, right] -> [mid+1, right]
55                left = mid + 1;
56            }
57        }
58        
59        return (int)left;
60    }
61};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.