410 Split Array Largest Sum

1. Question

Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.

Note: Ifnis the length of array, assume the following constraints are satisfied:

  • 1 ≤ n ≤ 1000

  • 1 ≤ m ≤ min(50,n)

Examples:

Input:

nums = [7,2,5,10,8]

m = 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.

2. Implementation

(1) Binary Search

思路:题目的本质是在这数组所有可能的m个subarray的最大sum里找一个最小的,可以利用二分法的思想,找到这个subarrat sum的左边界。做法是找出这个subarray sum的上下限,由于数组的所有元素都是非负的,所以上限就是数组总和,下限就是单独一个元素的最大值(注意,不是最小值,因为是找m个subarray里最大的一个),在这个范围里做二分

3. Time & Space Complexity

Binary Search: 时间复杂度O(nlog(maxSum - minSum + 1)), n是数组元素个数, 空间复杂度O(1)

Last updated

Was this helpful?