LeetCode 1043. Partition Array for Maximum Sum

原题链接在这里:https://leetcode.com/problems/partition-array-for-maximum-sum/

题目:

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. 1 <= K <= A.length <= 500
  2. 0 <= A[i] <= 10^6

题解:

When encounter such kind of problem.

Could think from a simpler example. Say only one element, then 2 elements and more. Virtualize them, find routines.

Use array dp to memorize maxmimum sum up to i.

If, A = [1], then A becomes A[1]. dp = [1].

A = [1, 15], then A becomes A[15, 15]. dp = [1, 30].

A = [1, 15, 7], then A becomes A[15, 15, 15]. dp = [1, 30, 45].

A = [1, 15, 7, 9], then A becomes A[15, 15, 15, 9]. dp = [1, 30, 45, 54].

...

The routine is like from i back k(<= K) steps, find the maxmimum element, curMax * k + dp[i-k](if available).

Finally return dp[A.length-1].

Time Complexity: O(n*K). n = A.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int maxSumAfterPartitioning(int[] A, int K) {
 3         int len = A.length;
 4         int [] dp = new int[len];
 5         for(int i = 0; i<len; i++){
 6             dp[i] = Integer.MIN_VALUE;
 7             int curMax = A[i];
 8             
 9             for(int k = 1; k<=K & i-k+1>=0; k++){
10                 curMax = Math.max(curMax, A[i-k+1]);
11                 dp[i] = Math.max(dp[i], (i-k<0 ? 0 : dp[i-k]) + curMax*k);
12             }
13         }
14         
15         return dp[len-1];
16     }
17 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11300836.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值