Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Split Array into K Subarrays
Minimize Largest Sum using Binary Search



Problem Statement

Given an array of non-negative integers and an integer K, split the array into K contiguous subarrays such that the maximum sum among these subarrays is minimized.

The goal is to make the largest sum among the K subarrays as small as possible.

If the array is empty or K is zero, return 0 as the answer.

Examples

Input ArrayKOutputDescription
[7, 2, 5, 10, 8]218Split as [7,2,5] and [10,8]. Max sum = 14 and 18 → answer is 18
[1, 2, 3, 4, 5]29Best split is [1,2,3] and [4,5] with max sums 6 and 9
[1, 4, 4]34Split each element as one subarray → max sum is 4
[5]15Only one element, one group → max sum = 5
[1, 2, 3]16All elements in one group → total sum = 6
[1, 2, 3]33Each element in its own group → largest is 3
[]30Empty array → no subarrays can be formed
[1, 2, 3]00Zero partitions not allowed → return 0
[10, 20, 30]530More partitions than elements → some will be empty, max element becomes answer

Solution

This problem asks us to split the array into K contiguous subarrays in such a way that the largest sum among these subarrays is as small as possible.

Understanding the Goal

We're not just trying to split the array randomly. We need to find a split where the heaviest load (the subarray with the highest sum) is minimized. Imagine splitting tasks across K workers, and you want to minimize the maximum load any one worker handles.

What Are We Really Searching For?

The answer is somewhere between:

  • The largest single element in the array (because no subarray can be smaller than this)
  • And the total sum of the array (if we don’t split it at all)

So, we’re trying to find the minimum possible value of the largest subarray sum — such that we can split the array into exactly K subarrays without any subarray exceeding that sum.

How We Approach It

We use binary search on the answer space. Instead of iterating through all ways to split (which is slow), we guess a value and check if it's possible to split the array using that as the maximum allowed subarray sum. Based on whether it's possible or not, we adjust our guess (just like binary search).

What Happens in Different Cases?

  • If the array is empty, we return 0 since there’s nothing to split.
  • If K is 0, we cannot make any valid partitions, so again return 0.
  • If K ≥ array length, the best case is to assign each number to its own subarray — so the largest element in the array becomes the answer.
  • If K = 1, we have to take the whole array as one subarray, so the total sum is the answer.
  • Normal case: We keep checking possible max sums using binary search, and count how many subarrays we need if we restrict the max sum to our current guess. If we need ≤ K subarrays, we try a smaller sum. If we need more than K, we increase the sum.

This method gives us the smallest possible largest subarray sum that still allows splitting the array into exactly K subarrays.

Why Binary Search Works

We’re using binary search over a range of answers — the range between the largest element and the sum of all elements. We're not searching inside the array but rather searching through all possible values the final answer can take. It’s efficient and brings the complexity down to O(n log(sum)).

Visualization

Algorithm Steps

  1. Set low = max(arr) and high = sum(arr).
  2. While low ≤ high:
  3. → Compute mid = (low + high) / 2.
  4. → Check if it’s possible to split the array into ≤ K subarrays where no subarray has sum > mid.
  5. → If possible, update answer = mid and try a smaller value by high = mid - 1.
  6. → Else, try a larger value by low = mid + 1.
  7. Return the minimum value stored in answer.

Code

Java
Python
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
public class SplitArrayLargestSum {
  public static int splitArray(int[] nums, int k) {
    int low = Integer.MIN_VALUE;
    int high = 0;
    for (int num : nums) {
      low = Math.max(low, num); // Minimum possible max sum is the largest element
      high += num;              // Maximum possible max sum is sum of all elements
    }

    int result = high;
    while (low <= high) {
      int mid = low + (high - low) / 2;
      if (canSplit(nums, k, mid)) {
        result = mid;         // Try a smaller maximum sum
        high = mid - 1;
      } else {
        low = mid + 1;        // Increase allowed max sum
      }
    }
    return result;
  }

  private static boolean canSplit(int[] nums, int k, int maxSum) {
    int currentSum = 0;
    int splits = 1;
    for (int num : nums) {
      if (currentSum + num > maxSum) {
        splits++;
        currentSum = num;
        if (splits > k) return false; // Too many splits needed
      } else {
        currentSum += num;
      }
    }
    return true;
  }

  public static void main(String[] args) {
    int[] arr = {7, 2, 5, 10, 8};
    int k = 2;
    System.out.println("Minimum largest sum: " + splitArray(arr, k));
  }
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n log(sum - max))We perform binary search over the range from max element to sum of all elements, and in each step, we scan the array once.
Average CaseO(n log(sum - max))For each binary search iteration, we check if the array can be split into K subarrays using a greedy scan.
Average CaseO(n log(sum - max))Even in the worst case, binary search narrows down the search space logarithmically, with O(n) work per step.

Space Complexity

O(1)

Explanation: No extra space is used except a few variables for tracking sums and counters.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M