410. Split Array Largest Sum

Given an array which consists of non-negative integers and an integerm, you can split the array intomnon-empty continuous subarrays. Write an algorithm to minimize the largest sum among thesemsubarrays.

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.
class Solution {
    public int splitArray(int[] nums, int m) {
        int n = nums.length; 
        int[][] dp = new int[n + 1][m + 1];
        int[] sums = new int[n + 1];

        for (int i = 0; i <= n; i++){
            for (int j = 0; j <= m; j++){
                dp[i][j] = Integer.MAX_VALUE;
            }
        }

        for (int i = 0; i < n; i++){
            sums[i + 1] = sums[i] + nums[i];
        }

        dp[0][0] = 0;
        for (int i = 1; i <= n; i++){
            for (int j = 1; j <= m; j++){
                for (int k = 0; k < i; k++){
                    dp[i][j] = Math.min(dp[i][j], Math.max(dp[k][j - 1], sums[i] - sums[k]));
                }
            }
        }

        return dp[n][m];
    }
}

results for ""

    No results matching ""