#410

Split Array Largest Sum

Hard
ArrayBinary SearchDynamic ProgrammingGreedyPrefix SumBinary SearchGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log(sum))
Space
O(1)
O(1)
💡

Intuition

Time O(n log(sum))Space O(1)

The optimal approach uses binary search combined with a greedy strategy. We search for the minimum possible largest sum that can be achieved by splitting the array into k subarrays. This is efficient because it narrows down the possible sums quickly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Set the left boundary of the binary search to the maximum element in nums and the right boundary to the sum of all elements in nums.
  2. 2Step 2: While left is less than right, calculate the mid-point and check if it's possible to split the array into k subarrays with this mid-point as the largest sum.
  3. 3Step 3: If it's possible, move the right boundary to mid; otherwise, move the left boundary to mid + 1.
  4. 4Step 4: Return the left boundary, which will be the minimized largest sum.
solution.py22 lines
1# Full working Python code
2def canSplit(nums, maxSum, k):
3    currentSum = 0
4    count = 1
5    for num in nums:
6        currentSum += num
7        if currentSum > maxSum:
8            currentSum = num
9            count += 1
10            if count > k:
11                return False
12    return True
13
14def splitArray(nums, k):
15    left, right = max(nums), sum(nums)
16    while left < right:
17        mid = (left + right) // 2
18        if canSplit(nums, mid, k):
19            right = mid
20        else:
21            left = mid + 1
22    return left

Complexity note: The time complexity is O(n log(sum)), where n is the length of the array and sum is the total sum of the array. The log(sum) comes from the binary search over possible sums, and O(n) is for checking if a split is possible.

  • 1The largest sum of any subarray must be at least the maximum element in the array.
  • 2The minimized largest sum can never be less than the average of the total sum divided by k.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.