Leetcode 3046. Split the Array
You are given an integer array nums
and an integer k
.
Partition the array into k
adjacent (non-empty) subarrays, where the largest sum of these subarrays is minimized.
Return the minimized largest sum of the partition.
Example:
Input
: nums = [7,2,5,10,8], k = 2
Output
: 18
Explanation
: There are four ways to split nums
into two subarrays:
Constraints:
k
adjacent subarrays.1 <= k <= min(50, nums.length)
, so it will always be valid to partition in a meaningful way.max(nums)
) and the sum of all elements (sum(nums)
).k
parts. If you can partition nums
within this limit, the value is valid.public class Solution {
public int splitArray(int[] nums, int k) {
int left = 0;
int right = 0;
for (int num : nums) {
left = Math.max(left, num);
right += num;
}
while (left < right) {
int mid = left + (right - left) / 2;
if (canSplit(nums, k, mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private boolean canSplit(int[] nums, int k, int maxSum) {
int currentSum = 0;
int subarrays = 1;
for (int num : nums) {
if (currentSum + num > maxSum) {
subarrays++;
currentSum = num;
if (subarrays > k) {
return false;
}
} else {
currentSum += num;
}
}
return true;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {7, 2, 5, 10, 8};
int k = 2;
System.out.println(sol.splitArray(nums, k)); // Outputs: 18
}
}
max(nums)
and sum(nums)
gives a time complexity of O(log(sum(nums) - max(nums)))
O(n)
where n
is the length of nums
.Thus, the overall time complexity is O(n * log(sum(nums) - max(nums)))
. This is efficient given the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?