DSA AnimatorREVISION VIDEOS
← Back to problems
New

Split Array Largest Sum — LeetCode 410 video explanation

Split the array into k non-empty contiguous parts. Minimize the largest sum among the parts.

Loading videos…

DSA Animator › DSA Revision › Binary Search › Split Array Largest Sum

Key moments in the Split Array Largest Sum video

0:04Problem0:10Example0:18Brute force0:26Key idea0:35Dry run0:48Code1:00Takeaway

What you will learn

Remember: minimize the largest part sum by binary searching that sum. This same template solves shipping, books and painters. The video solves Split Array Largest Sum (LeetCode 410, Hard) with the Binary Search on Answer pattern from the Binary Search topic, and you can replay every step in the interactive Split Array Largest Sum animation.

Split Array Largest Sum video transcript

Problem

Split the array into k non-empty contiguous parts. Minimize the largest sum among the parts.

Example

For 7, 2, 5, 10, 8 with k equal to 2, the best split is 7, 2, 5 and 10, 8. The largest sum is 18.

Brute force

Trying every way to place the cuts grows very fast. Dynamic programming works, but binary search is simpler and faster.

Key idea

Guess a limit for the largest sum. Fill parts greedily, and count how many parts that limit needs. If it needs at most k parts, the limit works, so try smaller.

Dry run

The range is 10, the biggest number, to 32, the total. Limit 21 works with 2 parts. 15 needs 3 parts, which is too many. 18 works, and 17 does not. So the answer is 18.

Code

In code, low is the maximum and high is the sum. The check returns how many parts a limit needs. Move high to mid when it fits in k parts, otherwise move low past mid. It's O of n log of the sum.

Takeaway

Remember: minimize the largest part sum by binary searching that sum. This same template solves shipping, books and painters.

More Binary Search revision videos

← All 185 DSA revision videos