博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 1043. Partition Array for Maximum Sum
阅读量:4622 次
发布时间:2019-06-09

本文共 1541 字,大约阅读时间需要 5 分钟。

原题链接在这里:

题目:

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 = 3Output: 84Explanation: 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
=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

你可能感兴趣的文章
Chapter 4 Syntax Analysis
查看>>
vi/vim使用
查看>>
讨论Spring整合Mybatis时一级缓存失效得问题
查看>>
Maven私服配置Setting和Pom文件
查看>>
Linux搭建Nexus3.X构建maven私服
查看>>
NPOI 操作Excel
查看>>
MySql【Error笔记】
查看>>
vue入门
查看>>
JS线程Web worker
查看>>
Flex的动画效果与变换!(三)(完)
查看>>
mysql常见错误码
查看>>
Openresty 与 Tengine
查看>>
使用XV-11激光雷达做hector_slam
查看>>
布局技巧4:使用ViewStub
查看>>
学习记事
查看>>
java 子类重写父类的方法应注意的问题
查看>>
[LevelDB] LevelDB理论基础
查看>>
【codecombat】 试玩全攻略 第一关kithguard地牢
查看>>
【DP】 POJ 1191 棋盘分割 记忆化搜索
查看>>
自动化测试 Appium之Python运行环境搭建 Part2
查看>>