Input:
nums =[7,2,5,10,8], k =2Output:
18Explanation:
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.
Define the lower bound - The smallest possible value for the largest sum is the maximum value in the nums array (since each subarray must be non-empty and an individual element itself could be the largest). low = 10
Define the upper bound - The largest possible value for the largest sum is the sum of all elements in the nums array (if we only had one subarray). high = 32
Use the canSplit function to check if it is possible to split the array into k or fewer subarrays such that the sum of each subarray does not exceed mid.
Adjust low and high based on the result of canSplit.
classSolution {
publicintsplitArray(int[] nums, int k) {
int low = 0, high = 0; // using long for sumfor (int num: nums) {
low = Math.max(num, low);
high += num;
}
if (k == 1) {
return high;
}
int ans = 0;
while (low <= high) {
int mid = (low + high) / 2;
if (canSplit(nums, k, mid)) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
privatebooleancanSplit(int[] nums, int k, int maxSum) {
int currentSum = 0;
int subarrays = 1; // Start with one subarrayfor (int num: nums) {
// If adding this element to the current subarray exceeds maxSum// then start a new subarrayif (currentSum + num > maxSum) {
subarrays++;
currentSum = num; // Start new subarray with the current numberif (subarrays > k) {
returnfalse; // More subarrays than allowed }
} else {
currentSum += num;
}
}
returntrue;
}
}