当前位置:网站首页>LeetCode 1043. 分隔数组以得到最大和 每日一题
LeetCode 1043. 分隔数组以得到最大和 每日一题
2022-07-07 15:32:00 【@小红花】
问题描述
给你一个整数数组 arr,请你将该数组分隔为长度最多为 k 的一些(连续)子数组。分隔完成后,每个子数组的中的所有值都会变为该子数组中的最大值。
返回将数组分隔变换后能够得到的元素最大和。
注意,原数组和分隔后的数组对应顺序应当一致,也就是说,你只能选择分隔数组的位置而不能调整数组中的顺序。
示例 1:
输入:arr = [1,15,7,9,2,5,10], k = 3
输出:84
解释:
因为 k=3 可以分隔成 [1,15,7] [9] [2,5,10],结果为 [15,15,15,9,10,10,10],和为 84,是该数组所有分隔变换后元素总和最大的。
若是分隔成 [1] [15,7,9] [2,5,10],结果就是 [1, 15, 15, 15, 10, 10, 10] 但这种分隔方式的元素总和(76)小于上一种。
示例 2:输入:arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
输出:83
示例 3:输入:arr = [1], k = 1
输出:1
提示:
1 <= arr.length <= 500
0 <= arr[i] <= 109
1 <= k <= arr.length来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/partition-array-for-maximum-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java
class Solution {
public int maxSumAfterPartitioning(int[] arr, int k) {
int n = arr.length;
int[] dp = new int[n];
for(int i = 0;i < k;i++){
dp[i] = getMaxValue(arr,0,i) * (i + 1);
}
for(int i = k;i < n;i++){
for(int j = 1;j <= k;j++){
dp[i] = Math.max(dp[i],dp[i - j] + getMaxValue(arr,i - j + 1,i) * j);
}
}
return dp[n - 1];
}
//得到指定区间的最大值
public int getMaxValue(int[] arr,int left,int right){
int ans = 0;
for(int i = left;i <= right;i++){
ans = Math.max(ans,arr[i]);
}
return ans;
}
}
边栏推荐
- logback. XML configure logs of different levels and set color output
- 【HCSD大咖直播】亲授大厂面试秘诀-简要笔记
- Record the migration process of a project
- Leetcode-136- number that appears only once (solve with XOR)
- Master this promotion path and share interview materials
- 应用在温度检测仪中的温度传感芯片
- C语言进阶——函数指针
- [PHP] PHP interface inheritance and interface multi inheritance principle and implementation method
- Personal notes of graphics (2)
- 【DesignMode】代理模式(proxy pattern)
猜你喜欢
随机推荐
[summary of knowledge] summary of notes on using SVN in PHP
How does laravel run composer dump autoload without emptying the classmap mapping relationship?
最新阿里P7技术体系,妈妈再也不用担心我找工作了
应用在温度检测仪中的温度传感芯片
QT中自定义控件的创建到封装到工具栏过程(二):自定义控件封装到工具栏
Asyncio concept and usage
Laravel5.1 Routing - routing packets
Tragedy caused by deleting the console statement
字节跳动Android金三银四解析,android面试题app
Personal notes of graphics (1)
Tidb cannot start after modifying the configuration file
Build an all in one application development platform, light flow, and establish a code free industry benchmark
在哪个期货公司开期货户最安全?
ATM系统
[designmode] flyweight pattern
Pycharm terminal enables virtual environment
JS 模块化
【C 语言】 题集 of Ⅹ
How can laravel get the public path
记一次项目的迁移过程