410. Split Array Largest Sum

  • Difficulty: Hard

  • Topics: Binary Search, Dynamic Programming

  • Similar Questions:

Problem:

Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.

Note:
If n is 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. </pre> </p>

Solutions:

class Solution {
public:
    int splitArray(vector<int>& nums, int m) {
        int n = nums.size();

        // not finalize
        vector<vector<long>> dp(m + 1, vector<long>(n + 1, INT_MAX));
        dp[0][0] = 0;

        for (int i = 1; i <= m; ++i) {
            for (int j = i; j <= n; ++j) {
                long sum = 0;
                dp[i][j] = INT_MAX;
                for (int k = 0; k <= j - i; ++k) {
                    sum += nums[j - 1 - k];
                    dp[i][j] = min(dp[i][j], max(sum, dp[i-1][j - k -1] ));
                }
                //cout << i << " " << j << " " << dp[i][j] << endl;
            }
        }


        return dp[m][n];

        //dp[i][j] = min(dp[i-1][0..k], sigma(nums[k..j]))
    }
};

results matching ""

    No results matching ""