Split Array Largest Sum⚓︎
Description⚓︎
Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.
Return the minimized largest sum of the split.
A subarray is a contiguous part of the array.
Example 1:
- Input:
nums = [7,2,5,10,8], k = 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.
Example 2:
- Input:
nums = [1,2,3,4,5], k = 2 - Output:
9 - Explanation:
There are four ways to split nums into two subarrays. The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.
Constraints:
1 <= nums.length <= 10000 <= nums[i] <= 10^61 <= k <= min(50, nums.length)
Solution⚓︎
Algorithm and Steps:
- Binary Search Range Initialization:
- Initialize two pointers,
landr, to -1 andINT_MAX, respectively.lis set to -1 to handle edge cases (like an array of [0]), andris the maximum possible value.
- Initialize two pointers,
- Binary Search:
- While
l + 1 < r, calculatemidas the average oflandr. Thismidvalue represents a candidate for the maximum sum of subarrays. - If
check(nums, k, mid)returnstrue, it means we can split the array intokor fewer subarrays where the maximum sum of any subarray ismidor less. In this case, updatertomid. - If
check(nums, k, mid)returnsfalse, it means splitting the array intoksubarrays with a maximum sum ofmidis not possible, so updateltomid.
- While
- Greedy Check Function:
checkis a helper function that takes the currentmidvalue and checks if it's possible to split the array intokor fewer parts without exceedingmidin any part.- Iterate through the array
nums. Accumulate the sum of elements and keep track of the number of parts (cnt) formed. - If adding the next element to the current sum exceeds
mid, incrementcntand start a new part with the current element as its first element. - If an element itself is greater than
mid, it's impossible to split the array as required, so returnfalse. - After iterating through all elements, if there's a non-zero sum remaining, increment
cnt. Then, return whethercntis less than or equal tok.
Complexity Analysis:
Time Complexity:
- The binary search runs in \(O(\log (\mathrm{INT\_ MAX}))\), which is essentially \(O(\log n)\) since \(\mathrm{INT\_ MAX}\) is a constant.
- Each call to
checkrequires \(O(n)\) time to go through the array. - Therefore, the total time complexity is \(O(n \log n)\), where n is the size of the array.
Space Complexity:
- The space complexity is \(O(1)\), as only a constant amount of additional space is used for variables and no additional data structures are employed.