Problem Description
Given an integer array nums and an integer k, split nums into k non-empty contiguous subarrays such that the largest sum among these subarrays is minimized.
Key Insights
- Use binary search over the answer: the candidate value is the maximum subarray sum.
- The lower bound of the search is max(nums) and the upper bound is sum(nums).
- A greedy approach is used to check if a candidate maximum sum allows splitting nums into at most k subarrays.
- Adjust the binary search bounds based on the feasibility check.
Space and Time Complexity
Time Complexity: O(n * log(sum(nums))) – n elements are processed for each binary search iteration. Space Complexity: O(1) – Constant extra space is used.
Solution
The solution employs binary search to determine the smallest maximum subarray sum possible. We set the initial lower bound to the maximum element and the upper bound to the total sum of the array. For each candidate value (mid), we check if the array can be split into k or fewer subarrays without any subarray sum exceeding mid using a greedy approach. If possible, we try to lower the candidate; if not, we increase the candidate. This continues until the optimal solution is found.