Naive 2D DP, can reduce to 1D


  • 0

    // Naive 2D DP

    public class Solution {
        public int splitArray(int[] nums, int m) {
            if (nums == null || nums.length == 0) return 0;
            int n = nums.length;
            int[][] dp = new int[m][n];
            // init first row: 0 split, running sum
            int sum = 0;
            for (int j = 0; j < n; j++) {
                sum += nums[j];
                dp[0][j] = sum;
            }
            for (int i = 1; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (j < i) {
                        dp[i][j] = 0;
                        continue;
                    }
                    dp[i][j] = Integer.MAX_VALUE;
                    for (int k = j - 1; k >= 0; k--) {
                        dp[i][j] = Math.min(dp[i][j], Math.max(dp[i - 1][k], dp[0][j - 1] - dp[0][k] + nums[j]));
                    }
                }
            }
            return dp[m - 1][n - 1];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.