Menu
CoddyTech

Split Array Largest Sum

You get an array nums of non-negative integers and an integer k. Cut nums into exactly k parts, where each part is a non-empty run of neighbouring values and the parts keep their order. Every part has a sum, and the cost of a split is the largest of those sums.

Return the smallest cost that any split into k parts can reach.

Function

splitArray(nums: integer-array, k: integer) → integer
numsinteger-array
the non-negative values, in order
kinteger
the number of contiguous parts to cut them into
Returnsinteger
the smallest possible value of the largest part sum

Constraints

  • 1 ≤ nums.length ≤ 5000
  • 0 ≤ nums[i] ≤ 105
  • 1 ≤ k ≤ nums.length
  • Every part holds at least one value. A part whose values are all 0 sums to 0, which is allowed.

Examples

Input
nums = [6, 2, 9, 4, 7, 3]k = 3
Output
13
Explanation
The split [6, 2], [9, 4], [7, 3] has sums 8, 13 and 10, so its cost is 13. No split costs 12: packing parts left to right with every sum at most 12 gives [6, 2], [9], [4, 7], [3], four parts where only three are allowed.

lock icon+20 hidden tests on Submit

challenge icon

Follow-up

Each greedy check reads all n values. With prefix sums, a check can find where each part ends by binary search instead. How fast does the whole method get when k is small and nums is long?

Reset code
def splitArray(nums, k):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [6, 2, 9, 4, 7, 3]
k = 3

Expected

13