Array Partition (k groups) for Sum or Average

这类题,dp数组总长度要加1,表示前n个数的最优值

·1043. Partition Array for Maximum Sum
https://leetcode.com/problems/partition-array-for-maximum-sum/

int maxSumAfterPartitioning(vector& arr, int k) {
        int n = arr.size();
        vector dp(n+1);
        for(int i=1; i<=n; ++i){
            int max_num = INT_MIN;
            for(int j=1; j<=k && i-j>=0; ++j){
                max_num = max(max_num, arr[i-j]);
                dp[i] = max(dp[i], dp[i-j] + max_num * j);
            }
        }
        
        return dp[n];
    }

·813. Largest Sum of Averages
https://leetcode.com/problems/largest-sum-of-averages/

double largestSumOfAverages(vector& A, int K) {
        int n = A.size();
        vector> dp(n+1, vector(K+1, 0.0));
        vector sums(n+1, 0.0);
        
        for(int i=1; i<=n; ++i){
            sums[i] = sums[i-1] + A[i-1];
            dp[i][1] = (double)sums[i] / i;
        }
        
        for(int k=2; k<=K; ++k){
            for(int i=1; i<=n; ++i){
                for(int j=0; j

`410. Split Array Largest Sum
https://leetcode.com/problems/split-array-largest-sum/

int splitArray(vector& nums, int m) {
        int n = nums.size();
        vector> dp(n+1, vector(m+1, INT_MAX));
        vector sums(n+1);
        for(int i=1; i<=n; ++i){
            sums[i] = sums[i-1] + nums[i-1];
        }
        
        for(int i=1; i<=n; ++i){
            dp[i][1] = sums[i];
        }
        
        for(int k=2; k<=m; ++k){
            for(int i=1; i<=n; ++i){
                for(int j=0; j

你可能感兴趣的:(Array Partition (k groups) for Sum or Average)