Leetcode 1043. Partition Array for Maximum Sum (Medium)(直观分析)

Description:

Given an integer array A, you partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values changed to become the maximum value of that subarray.

Return the largest sum of the given array after partitioning.

Example 1:
Input: A = [1,15,7,9,2,5,10], K = 3
Output: 84
Explanation: A becomes [15,15,15,9,10,10,10]
Note:
1 <= K <= A.length <= 500
0 <= A[i] <= 10^6

Analysis:

Use dp[i] to denote the maximum sum of first i items of the array after partitioning.
d p [ i ] = m a x { d p [ i − 1 ] + A [ i − 1 ] ∗ 1 d p [ i − 2 ] + m a x { A [ i − 2 ] , A [ i − 1 ] } ∗ 2 d p [ i − 3 ] + m a x { [ A [ i − 3 ] , A [ i − 2 ] , A [ i − 1 ] } ∗ 3 dp[i] = max \begin{cases} dp[i-1] + A[i-1] * 1 \\ dp[i-2] + max\{A[i-2], A[i-1]\} * 2 \\ dp[i-3] + max\{[A[i-3], A[i-2], A[i-1]\} * 3 \\ \end{cases} dp[i]=maxdp[i1]+A[i1]1dp[i2]+max{A[i2],A[i1]}2dp[i3]+max{[A[i3],A[i2],A[i1]}3


Code:
class Solution {
    public int maxSumAfterPartitioning(int[] A, int K) {
        int n = A.length; 
        int[] dp = new int[n+1];
        for(int i = 1; i <= n; i++) {
            int curMax = 0;
            for(int j = 1; j <= K; j++) {
                if((i-j)>=0){
                    curMax = Math.max(curMax, A[i-j]);
                    dp[i] = Math.max(dp[i], dp[i-j] + curMax*j);
                }
            }
        }
        return dp[n];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值