Taro Logo

Split Array Largest Sum

#111 Most AskedHard
0 views
Topics:
ArraysBinary Search

Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.

Return the minimized largest sum of the split.

A subarray is a contiguous part of the array.

Example 1:

Input: nums = [7,2,5,10,8], k = 2
Output: 18
Explanation: 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.

Example 2:

Input: nums = [1,2,3,4,5], k = 2
Output: 9
Explanation: There are four ways to split nums into two subarrays.
The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.

Constraints:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 106
  • 1 <= k <= min(50, nums.length)

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the array contain negative numbers, or are all integers guaranteed to be non-negative?
  2. What should be returned if $k$ is greater than the total number of elements in the array?
  3. Are the resulting subarrays required to be contiguous sections of the original array, or can elements be picked from anywhere?
  4. What is the expected range of values for the elements in `nums` and for the integer `k`?
  5. If $k$ is equal to 1, should the returned sum simply be the sum of all elements in the entire array?

Brute Force Solution

Approach

Imagine you have a row of numbers that you need to divide into a specific number of groups. The brute force strategy involves testing every single possible place you could draw boundary lines to create the groups.

Here's how the algorithm would work step-by-step:

  1. Look at the full collection of numbers laid out in front of you.
  2. Imagine sliding divider lines between the numbers to split them into the required number of groups.
  3. Try the very first combination of divider placements, which might mean grouping the first few numbers together, the next few in the second group, and so on.
  4. For this specific grouping, calculate the sum of numbers inside every single group.
  5. Find the largest group sum from that specific arrangement, because that represents the score for this particular way of splitting.
  6. Write down this score and then move the divider lines slightly to try a brand new way of splitting the numbers.
  7. Repeat this process for every conceivable place the divider lines could possibly go.
  8. Once you have checked every single valid combination of group splits, look back at all your saved scores.
  9. Pick the smallest maximum sum you found during your search, as that represents the best possible outcome.

Code Implementation

class Solution:
    def splitArray(self, collection_of_numbers: list[int], target_number_of_groups: int) -> int:
        total_elements_count = len(collection_of_numbers)
        
        # We use a recursive helper to explore all valid combinations of splitting divider lines
        def explore_all_splits(current_index: int, remaining_groups: int) -> int:
            if remaining_groups == 1:
                return sum(collection_of_numbers[current_index:])
            
            minimum_largest_sum = float('inf')
            current_running_sum = 0
            
            for split_index in range(current_index, total_elements_count - remaining_groups + 1):
                current_running_sum += collection_of_numbers[split_index]
                largest_sum_from_future = explore_all_splits(split_index + 1, remaining_groups - 1)
                current_arrangement_score = max(current_running_sum, largest_sum_from_future)
                minimum_largest_sum = min(minimum_largest_sum, current_arrangement_score)
                
                if current_running_sum > minimum_largest_sum:
                    break
            
            return minimum_largest_sum

        # Start the recursive brute force search from the very beginning with the full group count
        return explore_all_splits(0, target_number_of_groups)

Big(O) Analysis

Time Complexity
O(C(n-1, k-1) * n) – To evaluate every possible way to split the array of size n into k groups, we must test all combinations of placing k-1 dividers among the n-1 available spaces. The number of ways to place these dividers is given by the binomial coefficient C(n-1, k-1). For each of these distinct divider arrangements, we iterate through the groups to calculate their sums and find the maximum, which takes linear time proportional to n. Multiplying the number of combinations by the cost of checking each arrangement results in approximately C(n-1, k-1) * n operations, which simplifies to an exponential time complexity of O(C(n-1, k-1) * n).
Space Complexity
O(1) – The auxiliary space used by this algorithm is strictly constant because we only maintain a few primitive tracking variables for our binary search bounds, such as the low, high, and mid pointers. We do not allocate any dynamic data structures, temporary arrays, or hash maps that scale with the input size N. Furthermore, since the approach relies on an iterative binary search rather than recursion, there is no call stack memory consumed. Thus, regardless of how large the input array grows, the extra memory remains fixed at O(1).

Optimal Solution

Approach

Instead of guessing every possible way to divide the collection of items, we use a smart guessing strategy paired with elimination. We test a potential maximum capacity, and if it is too small to fit everything within our allowed number of groups, we know our guess was too low and adjust accordingly.

Here's how the algorithm would work step-by-step:

  1. Figure out the absolute lowest possible capacity we could ever need, which is simply the size of the single largest item in our collection.
  2. Figure out the absolute highest possible capacity we could ever need, which is the sum of all the items combined if we were forced to put them all together.
  3. Take the middle point between this lowest and highest possible capacity as our current test guess.
  4. Simulate dividing our collection into groups by adding items one by one until adding the next item would exceed our test guess capacity, then start a new group.
  5. Count how many total groups were needed using this test guess.
  6. If the number of groups we used is greater than our allowed limit, it means our test guess capacity was too strict, so throw away all guesses lower than or equal to this test capacity and try a higher range.
  7. If the number of groups we used is within our allowed limit, it means our test guess capacity might work, but a smaller capacity might work even better, so save this successful guess and try a lower range.
  8. Repeat this narrowing down process until the lowest and highest possibilities meet, giving us the absolute minimum possible largest sum.

Code Implementation

class Solution:
    def splitArray(self, collection_items: list[int], allowed_groups: int) -> int:
        lowest_possible_capacity = max(collection_items)
        highest_possible_capacity = sum(collection_items)
        optimal_largest_sum = highest_possible_capacity

        while lowest_possible_capacity <= highest_possible_capacity:
            test_guess_capacity = (lowest_possible_capacity + highest_possible_capacity) // 2
            
            # We test this capacity to see how many groups are required to fit all items.
            groups_needed = 1
            current_group_sum = 0
            for item_value in collection_items:
                if current_group_sum + item_value > test_guess_capacity:
                    groups_needed += 1
                    current_group_sum = item_value
                else:
                    current_group_sum += item_value

            # If we exceed the allowed groups, our capacity is too small and must be increased.
            if groups_needed > allowed_groups:
                lowest_possible_capacity = test_guess_capacity + 1
            else:
                optimal_largest_sum = test_guess_capacity
                highest_possible_capacity = test_guess_capacity - 1

        # Once search boundaries meet, we have found the absolute minimum possible largest sum.
        return optimal_largest_sum

Big(O) Analysis

Time Complexity
O(n log S) – The binary search runs over a range of possible sums S, which spans from the maximum element to the sum of all elements, taking log S iterations. Inside this search, we linearly scan the array of size n to simulate group creation and count the total groups needed for our test guess. Multiplying the search steps by the linear scan cost yields approximately n * log S operations, which simplifies to O(n log S).
Space Complexity
O(1) – The algorithm only uses a few primitive variables like pointers for the lowest and highest capacity bounds, the current middle test guess, and counters for the groups. These few scalar variables take a constant amount of memory regardless of how large the input array of items is. Because no extra data structures, recursion stacks, or auxiliary arrays scale with the input size N, the auxiliary space complexity remains strictly constant.

Edge Cases

k equals the length of the array
How to Handle:
The binary search lower bound will correctly be the maximum single element in the array, representing each element as its own subarray.
k equals 1
How to Handle:
The binary search upper bound will correctly be the sum of all elements in the array, representing the entire array as a single subarray.
Array contains all identical values
How to Handle:
The binary search quickly converges on the optimal evenly-distributed subarray sums because the feasibility function evaluates ranges uniformly.
Array contains zeros
How to Handle:
Zeros are safely accommodated by the greedy partition check since they do not increase the running sum of a subarray.
Large array elements causing potential integer overflow when summing
How to Handle:
We use 64-bit integers for the binary search bounds and running sums to prevent arithmetic overflow during the feasibility checks.
k is greater than the length of the array
How to Handle:
Constraints typically guarantee k is less than or equal to the array length, making this an invalid input scenario.
Highly skewed distributions with extreme outliers
How to Handle:
The binary search lower bound automatically clamps to the largest single element, ensuring no subarray sum can be smaller than that maximum value.
Maximum possible array size and maximum element values
How to Handle:
The O(N log(Sum)) binary search time complexity scales efficiently and easily passes within standard execution time limits.
0/257 completed