Skip to main content

410. Split Array Largest Sum

This page provides solutions for the leetcode problem 410. Split Array Largest Sum.

Problem Explanation

The problem is asking us to split an array into K\text{K} subarrays in such a way that the largest sum of any subarray is minimized.

Solution

This problem can be solved using the Binary Search technique. More such questions can be found here.

class Solution {
public int splitArray(int[] nums, int k) {
int lo = Integer.MIN_VALUE;
int hi = 0;

for(int num: nums) {
lo = Math.max(lo, num);
hi += num;
}

while(lo < hi) {
int mid = lo + (hi - lo) / 2;
int partitions = getPartitions(nums, mid);
if (partitions > k) lo = mid + 1;
else hi = mid;
}
return lo;
}

private int getPartitions(int[] nums, int required) {
int index = 0, sum = 0, partition = 1;
while(index < nums.length) {
sum += nums[index];
if (sum > required) {
sum = nums[index];
partition++;
}
index++;
}
return partition;
}
}

Complexity

Let's say there are N\text{N} elements in an array, and total sum of all elements in an array is S\text{S}.

Time Complexity

The time complexity is O(logS)\text{O}(\log \text{S}) for searching the optimal solution using binary search, and O(N)\text{O}(\text{N}) for checking if the array can be split into K\text{K} subarrays., so total time complexity will be:

O(NlogS)\text{O}(\text{N} \log \text{S})

Space Complexity

The solution uses constant space for storing binary search variables, so space complexity will be:

O(1)\text{O}(1)