Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Split an array to minimise the largest part

Hard · Target 30 minutes · Binary search · Type asked atGoogle

Given an array nums of non-negative integers and an integer k, split nums into exactly k non-empty contiguous parts so that the largest part sum is as small as possible. Return that smallest possible largest sum.

Examples

InputOutputWhy
nums = [7, 2, 5, 10, 8], k = 218[7, 2, 5] and [10, 8].
nums = [1, 2, 3, 4, 5], k = 29[1, 2, 3] and [4, 5].
nums = [1, 4, 4], k = 34Each element alone.

Constraints

  • 1 ≤ k ≤ n ≤ 1000
  • 0 ≤ nums[i] ≤ 10⁶

Hints

Hint 1

Trying every way to place k − 1 cuts is exponential, and a dynamic program over (position, parts) is O(k · n²). There is a faster way to think about it.

Hint 2

Turn the question round: given a limit L, can the array be split into at most k parts with every part summing to at most L? A greedy scan answers that in O(n).

Hint 3

Feasibility is monotone in L: if a limit works, every larger limit works. So binary search L between max(nums) and sum(nums) for the smallest feasible value.

Where people lose marks

  • Starting the search at 0 or 1 instead of max(nums). Below the largest element no split is feasible, and the greedy check would loop or miscount.
  • Counting parts from 0 rather than 1: the scan always has one part open.
  • Searching for "exactly k" parts in the check. The greedy test answers "at most k", which is what makes it monotone.
  • Overflow when summing large arrays in languages with 32-bit integers; use 64-bit totals.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.