Split Array Largest Sum — LeetCode 410 Python Solution

HardGreedyArrayBinary SearchDynamic ProgrammingPrefix Sum
Problem
#410
Pattern
Prefix Sum
Reading time
3 min

The problem

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.

Example

Input
nums = [7,2,5,10,8], k = 2
Output
18
Explanation
There are four ways to split nums into two subarrays.

Python solution

Python
class Solution:
    def splitArray(self, nums: List[int], k: int) -> int:
        def check(mx):
            s, cnt = inf, 0
            for x in nums:
                s += x
                if s > mx:
                    s = x
                    cnt += 1
            return cnt <= k

        left, right = max(nums), sum(nums)
        return left + bisect_left(range(left, right + 1), True, key=check)

Complexity

MeasureComplexity
TimeO(n \times \log m)
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 410. Split Array Largest Sum is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 410. Split Array Largest Sum?
LeetCode 410. Split Array Largest Sum is rated Hard on LeetCode.
What is the time complexity of LeetCode 410. Split Array Largest Sum?
The Python solution on this page runs in O(n \times \log m).
What is the space complexity of LeetCode 410. Split Array Largest Sum?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 410. Split Array Largest Sum cover?
LeetCode 410. Split Array Largest Sum is tagged Greedy, Array, Binary Search, Dynamic Programming and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview