410. Split Array Largest Sum!
class Solution {
public int splitArray(int[] nums, int m) {
//dp[i][j] represents the largest sum of subarrary nums[0, j] that split into i part
//dp[1][j]==sum(nums[0,j])
//set 0<k<j
//dp[i][j]=min(dp[i-1][k], sum of nums[k+1,j])
int[][] memo = new int[m+1][nums.length];
// initialization
int sum=0;
for (int i=0; i<nums.length; i++){
sum+=nums[i];
memo[1][i]=sum;
}
// initialize dp[i][j];
for (int i=2; i<=m; i++){
// j=i-1: number of element cannot be less than i
for(int j=i-1; j<nums.length; j++){
//divide[0,j] into [0,k] and (k,j]
memo[i][j]=Integer.MAX_VALUE;
// k+1>=i-1 : number of elements in nums[0,k] (k+1) cannot be less than number of divided subarrays (i-1)
for(int k=i-2; k<j; k++){
memo[i][j]=Math.min(memo[i][j], Math.max(memo[i-1][k], memo[1][j]-memo[1][k]));
}
}
}
return memo[m][nums.length-1];
}
}
Last updated
Was this helpful?