<p>Given an integer array <code>nums</code> and an integer <code>k</code>, split <code>nums</code> into <code>k</code> non-empty subarrays such that the largest sum of any subarray is <strong>minimized</strong>.</p>

<p>Return <em>the minimized largest sum of the split</em>.</p>

<p>A <strong>subarray</strong> is a contiguous part of the array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [7,2,5,10,8], k = 2
<strong>Output:</strong> 18
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,4,5], k = 2
<strong>Output:</strong> 9
<strong>Explanation:</strong> There are four ways to split nums into two subarrays.
The best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>
	<li><code>1 &lt;= k &lt;= min(50, nums.length)</code></li>
</ul>

#      [7,2,5, 10,8]
# psum [0,7,9,14,24,32]
# sum [i,j] = psum[j+1] - psum[i]
# example sum [2,3] = psum[4] - psum[2] = 24 - 9 = 15

class Solution:
    def splitArray(self, nums: List[int], k: int) -> int:
        n = len(nums)
        psum = [0]*(n+1)
        for i in range(n):
            psum[i+1] = nums[i] + psum[i]

        @cache        
        def split(i, s):
            if s==0:
                return psum[n] - psum[i]
            
            # n-i is nums left, must be > s
            if n-i <= s:
                return 10**9

            
            best = 10**9
            for j in range(i, n-1):
                leftsum = psum[j+1] - psum[i]
                if leftsum > best:
                    return best
                rightsum = split(j+1, s-1)
                if rightsum == 10**9:
                    return best
                #print("split", i, j, "s=", s, "left", leftsum, "right", rightsum)
                best = min(best, max(leftsum, rightsum))
            return best

        return split(0, k-1)


23600