Split Array Largest Sum
Problem
Given an array of non-negative integers nums and an integer k, split nums into k non-empty continuous subarrays such that the largest sum among these subarrays is minimized, and return this minimized largest sum.
- 1 ≤ nums.length ≤ 10⁴
- 0 ≤ nums[i] ≤ 10⁶
- 1 ≤ k ≤ nums.length
Example
nums = [7,2,5,10,8], k = 218One optimal way to split is [7,2,5] and [10,8]. The sums are 14 and 18, so the largest sum is 18. Any other split results in a larger maximum subarray sum. A brute-force approach would try all possible splits, which is exponential. Instead, the algorithm uses binary search on the range between the largest single element (10) and the total sum (32). It tests midpoints to check if the array can be split into at most k subarrays with sums not exceeding the midpoint. The critical moment is when the midpoint 18 is tested and found feasible, allowing the search to narrow down to smaller sums until the minimal feasible largest sum is found.
Approach
Straightforward Solution
A brute-force approach enumerates all possible splits into k subarrays and calculates the largest sum for each, resulting in exponential time complexity, which is infeasible for large inputs.
Core Observation
The minimal largest sum after splitting lies between the maximum single element (lower bound) and the total sum of the array (upper bound). This range forms a search space for the answer.
Path to Optimal
Recognizing that the answer is a number within a bounded range, the problem transforms into a decision problem: 'Can the array be split into at most k subarrays with sums not exceeding a given value?' This monotonic property enables binary search on the answer space. The algorithm iteratively tests midpoints and adjusts the search boundaries based on feasibility, converging to the minimal largest sum.
Optimal Approach
Use binary search between max(nums) and sum(nums). For each candidate largest sum, greedily split the array into subarrays without exceeding this sum. If the number of subarrays needed is less than or equal to k, the candidate is feasible, and the search narrows to smaller sums. Otherwise, it moves to larger sums. This approach runs in O(n log(sum(nums))) time.
Time
O(n log S)
The binary search runs over the range from max(nums) to sum(nums), which is at most sum(nums) - max(nums). Each feasibility check iterates through nums once (O(n)). Thus, total time is O(n log S), where S = sum(nums).
Space
O(1)
The algorithm uses only a fixed number of variables for pointers and counters, with no additional data structures proportional to input size.
Pattern Spotlight
Binary Search on Answer Space (Feasibility Check)
When the problem asks for an optimal numeric value bounded by a range and feasibility can be checked in linear time, use binary search on the answer space by repeatedly testing midpoints and narrowing the range based on feasibility.
Solution
| 1 | class Solution: |
| 2 | def splitArray(self, nums: List[int], k: int) -> int: |
| 3 | def canSplit(max_allowed_sum): |
| 4 | subarrays = 1 |
| 5 | current_sum = 0 |
| 6 | |
| 7 | for num in nums: |
| 8 | if current_sum + num > max_allowed_sum: |
| 9 | subarrays += 1 |
| 10 | current_sum = 0 |
| 11 | |
| 12 | current_sum += num |
| 13 | |
| 14 | return subarrays <= k |
| 15 | |
| 16 | l, r = max(nums), sum(nums) |
| 17 | |
| 18 | while l < r: |
| 19 | max_allowed_sum = (l + r) // 2 |
| 20 | |
| 21 | if canSplit(max_allowed_sum): |
| 22 | r = max_allowed_sum |
| 23 | else: |
| 24 | l = max_allowed_sum + 1 |
| 25 | |
| 26 | return l |
| 1 | import java.util.List; |
| 2 | |
| 3 | public class Solution { |
| 4 | public int splitArray(List<Integer> nums, int k) { |
| 5 | int l = Integer.MIN_VALUE; |
| 6 | int r = 0; |
| 7 | for (int num : nums) { |
| 8 | if (num > l) { |
| 9 | l = num; |
| 10 | } |
| 11 | r += num; |
| 12 | } |
| 13 | |
| 14 | while (l < r) { |
| 15 | int maxAllowedSum = l + (r - l) / 2; |
| 16 | if (canSplit(nums, k, maxAllowedSum)) { |
| 17 | r = maxAllowedSum; |
| 18 | } else { |
| 19 | l = maxAllowedSum + 1; |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | return l; |
| 24 | } |
| 25 | |
| 26 | private boolean canSplit(List<Integer> nums, int k, int maxAllowedSum) { |
| 27 | int subarrays = 1; |
| 28 | int currentSum = 0; |
| 29 | |
| 30 | for (int num : nums) { |
| 31 | if (currentSum + num > maxAllowedSum) { |
| 32 | subarrays++; |
| 33 | currentSum = 0; |
| 34 | } |
| 35 | currentSum += num; |
| 36 | } |
| 37 | |
| 38 | return subarrays <= k; |
| 39 | } |
| 40 | } |
| 1 | #include <vector> |
| 2 | #include <algorithm> |
| 3 | |
| 4 | using namespace std; |
| 5 | |
| 6 | class Solution { |
| 7 | public: |
| 8 | int splitArray(vector<int>& nums, int k) { |
| 9 | int l = *max_element(nums.begin(), nums.end()); |
| 10 | long long r = 0; |
| 11 | for (int num : nums) { |
| 12 | r += num; |
| 13 | } |
| 14 | |
| 15 | while (l < r) { |
| 16 | int maxAllowedSum = l + (r - l) / 2; |
| 17 | if (canSplit(nums, k, maxAllowedSum)) { |
| 18 | r = maxAllowedSum; |
| 19 | } else { |
| 20 | l = maxAllowedSum + 1; |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | return l; |
| 25 | } |
| 26 | |
| 27 | private: |
| 28 | bool canSplit(const vector<int>& nums, int k, int maxAllowedSum) { |
| 29 | int subarrays = 1; |
| 30 | int currentSum = 0; |
| 31 | |
| 32 | for (int num : nums) { |
| 33 | if (currentSum + num > maxAllowedSum) { |
| 34 | subarrays++; |
| 35 | currentSum = 0; |
| 36 | } |
| 37 | currentSum += num; |
| 38 | } |
| 39 | |
| 40 | return subarrays <= k; |
| 41 | } |
| 42 | }; |
| 1 | var splitArray = function(nums, k) { |
| 2 | let l = Math.max(...nums); |
| 3 | let r = nums.reduce((a, b) => a + b, 0); |
| 4 | |
| 5 | function canSplit(maxAllowedSum) { |
| 6 | let subarrays = 1; |
| 7 | let currentSum = 0; |
| 8 | |
| 9 | for (const num of nums) { |
| 10 | if (currentSum + num > maxAllowedSum) { |
| 11 | subarrays++; |
| 12 | currentSum = 0; |
| 13 | } |
| 14 | currentSum += num; |
| 15 | } |
| 16 | |
| 17 | return subarrays <= k; |
| 18 | } |
| 19 | |
| 20 | while (l < r) { |
| 21 | const maxAllowedSum = Math.floor((l + r) / 2); |
| 22 | if (canSplit(maxAllowedSum)) { |
| 23 | r = maxAllowedSum; |
| 24 | } else { |
| 25 | l = maxAllowedSum + 1; |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | return l; |
| 30 | }; |
Step-by-Step Solution
Greedily Check Feasibility of a Candidate Largest Sum
| 3 | def canSplit(max_allowed_sum): |
| 4 | subarrays = 1 |
| 5 | current_sum = 0 |
| 7 | for num in nums: |
| 8 | if current_sum + num > max_allowed_sum: |
| 9 | subarrays += 1 |
| 10 | current_sum = 0 |
| 12 | current_sum += num |
| 14 | return subarrays <= k |
Objective
To determine if nums can be split into at most k subarrays such that no subarray sum exceeds max_allowed_sum.
Key Insight
By iterating through nums and accumulating sums, whenever adding the next number exceeds max_allowed_sum, a new subarray is started. Counting how many subarrays are needed reveals if the candidate sum is feasible. This greedy approach works because any valid split must respect the sum constraint, and the minimal number of subarrays for a given sum can be found in a single pass.
Interview Quick-Check
Core Logic
The feasibility check greedily forms subarrays by accumulating sums until exceeding max_allowed_sum, then starting a new subarray, ensuring the minimal number of subarrays for that sum.
State & Boundaries
Initialize subarrays count to 1 and current_sum to 0 before iterating through nums.
Common Pitfalls & Bugs
Forgetting to reset current_sum after starting a new subarray or miscounting subarrays leads to incorrect feasibility results.
Binary Search to Narrow Down the Minimal Largest Sum
| 16 | l, r = max(nums), sum(nums) |
| 18 | while l < r: |
| 19 | max_allowed_sum = (l + r) // 2 |
| 21 | if canSplit(max_allowed_sum): |
| 22 | r = max_allowed_sum |
| 23 | else: |
| 24 | l = max_allowed_sum + 1 |
| 26 | return l |
Objective
To iteratively adjust the search boundaries based on feasibility until the minimal largest sum is found.
Key Insight
Binary search exploits the monotonicity of the feasibility function: if a candidate sum is feasible, all larger sums are feasible; if not, all smaller sums are not feasible. By testing midpoints and moving boundaries accordingly, the algorithm converges to the smallest feasible sum efficiently.
Interview Quick-Check
Core Logic
Binary search updates the right boundary when the candidate sum is feasible and the left boundary when it is not, converging to the minimal feasible largest sum.
State & Boundaries
The search space is initialized between max(nums) and sum(nums), ensuring all candidates are valid sums.
Common Pitfalls & Bugs
Incorrectly updating boundaries or using non-integer midpoints can cause infinite loops or incorrect results.
Line Analysis
This solution has 4 Critical lines interviewers watch for.
if current_sum + num > max_allowed_sum:
Check if adding the current number exceeds max_allowed_sum.
This conditional is the critical decision point that enforces the sum constraint, ensuring subarrays do not exceed the candidate maximum sum.
return subarrays <= k
Return whether the number of subarrays is at most k.
Returning this condition encapsulates the feasibility test, enabling binary search to adjust boundaries based on whether the candidate sum is achievable.
if canSplit(max_allowed_sum):
Check if the array can be split with the current midpoint as max allowed sum.
This call is the core of the binary search decision, directly influencing boundary adjustments.
return l
Return the minimal largest sum found after binary search completes.
Returning left after the loop terminates guarantees the minimal largest sum that allows splitting into k subarrays.
current_sum = 0
Reset current_sum to 0 when starting a new subarray.
Resetting the sum ensures the new subarray starts fresh, correctly accumulating sums without carryover.
l, r = max(nums), sum(nums)
Initialize left boundary to the maximum element in nums.
The minimal largest sum cannot be less than the largest single element, establishing the lower bound of the search space.
r = max_allowed_sum
If feasible, move the right boundary to the midpoint.
Reducing the upper bound narrows the search to smaller sums, seeking a minimal feasible sum.
else:
If not feasible, move the left boundary above the midpoint.
Increasing the lower bound excludes infeasible sums, focusing on larger sums that might be feasible.
def canSplit(max_allowed_sum):
Define a helper function to check if nums can be split into at most k subarrays with sums not exceeding max_allowed_sum.
Encapsulating the feasibility check as a helper function isolates the decision logic, enabling clean binary search integration and repeated testing of candidate sums.
subarrays += 1
Increment the subarrays count when starting a new subarray.
Counting subarrays accurately is necessary to verify if the candidate sum allows splitting into at most k subarrays.
current_sum += num
Add the current number to current_sum.
Accumulate the sum of the current subarray to track its total and compare against max_allowed_sum.
max_allowed_sum = (l + r) // 2
Calculate the midpoint of the current search boundaries.
Midpoint selection divides the search space, enabling logarithmic convergence.
l = max_allowed_sum + 1
Adjust left boundary to midpoint plus one when infeasible.
Incrementing left ensures progress and prevents infinite loops when mid equals left.
subarrays = 1
Initialize the count of subarrays to 1.
Starting with one subarray assumes at least one subarray is needed; this count increments only when the current sum exceeds the allowed maximum.
current_sum = 0
Initialize current_sum to 0 to accumulate subarray sums.
Tracking the running sum of the current subarray is essential to determine when to start a new subarray.
while l < r:
Continue binary search while left is less than right.
This loop condition ensures the search space is narrowed until convergence to the minimal feasible sum.
for num in nums:
Iterate through each number in nums.
Processing each element sequentially allows the greedy accumulation of sums and subarray partitioning.
Test Your Understanding
Why does binary searching on the range between max(nums) and sum(nums) guarantee finding the minimal largest subarray sum?
Because the minimal largest sum must be at least the largest single element (since no subarray sum can be smaller) and at most the total sum (the entire array as one subarray). The feasibility function is monotonic: if a sum is feasible, all larger sums are also feasible, enabling binary search to find the minimal feasible sum.
Related Problems
Binary Search pattern
Don't just read it. Drill it.
Reconstruct Split Array Largest Sum from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Split Array Largest Sum drill