Sponsored
Sponsored
This approach uses binary search to efficiently find the minimized largest sum. The range for binary search is between the maximum single element in the array (lower bound) and the sum of the array (upper bound). For each candidate middle value in the binary search, we check if it's possible to partition the array into k or fewer subarrays such that none has a sum greater than this candidate. This check is done through a greedy approach: we iterate over the array, adding elements to a running sum until adding another element would exceed the candidate sum, at which point we start a new subarray.
Time Complexity: O(n log(sum - max)), where sum is the total sum of array and max is the maximum element.
Space Complexity: O(1), as no additional space proportional to input size is used.
1public class Solution {
2 public int SplitArray(int[] nums, int k) {
3 int left = nums.Max();
4 int right = nums.Sum();
5 while (left < right) {
6 int mid = (left + right) / 2;
7 int currentSum = 0, pieces = 1;
8 foreach (int num in nums) {
9 if (currentSum + num > mid) {
10 currentSum = num;
11 pieces++;
12 } else {
13 currentSum += num;
14 }
15 }
16 if (pieces > k) {
17 left = mid + 1;
18 } else {
19 right = mid;
20 }
21 }
22 return left;
23 }
24}
The C# solution executes a binary search on the available sums for subarrays, checking if the mid-point can be a valid limit for splitting into k subarrays. Adjustments to the search range are made in a loop, finalizing the minimized largest sum with the return statement.
We can also use dynamic programming to solve this problem by maintaining a DP table where dp[i][j] means the minimum largest sum for splitting the first i elements into j subarrays. The recurrence is based on considering different potential previous cut positions and calculating the maximum sum for the last subarray in each case, iterating across feasible positions.
Time Complexity: O(n^2 * k), as each subproblem depends on earlier solutions.
Space Complexity: O(n*k), for the dp table.
1
This C solution implements dynamic programming by using a dp table initialized with INT_MAX, with the exception of dp[0][0] set to 0 allowing split calculations. The recurrence is used to iterate over each possible partition configuration, minimizing the result stored at dp[k][numsSize].