[LeetCode] 689. Maximum Sum of 3 Non-Overlapping Subarrays 三个非重叠子数组的最大和
In a given array nums
of positive integers, find three non-overlapping subarrays with maximum sum.
Each subarray will be of size k
, and we want to maximize the sum of all 3*k
entries.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
Example:
Input: [1,2,1,2,6,7,5,1], 2
Output: [0, 3, 5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.
Note:
nums.length
will be between 1 and 20000.nums[i]
will be between 1 and 65535.k
will be between 1 and floor(nums.length / 3).
给一个由正数组成的数组,找三个长度为k的不重叠的子数组,使得三个子数组的数字之和最大。
解法: DP,思路类似于123. Best Time to Buy and Sell Stock III,先分别从左和右两个方向求出每一个位置i之前的长度为k的元素和最大值,这样做的好处是之后想要得到某一位置的最大和时能马上知道。然后在用一个循环找出三段的最大和。
Java:
class Solution {
public int[] maxSumOfThreeSubarrays(int[] nums, int k) {
int n = nums.length, maxsum = 0;
int[] sum = new int[n+1], posLeft = new int[n], posRight = new int[n], ans = new int[3];
for (int i = 0; i < n; i++) sum[i+1] = sum[i]+nums[i];
// DP for starting index of the left max sum interval
for (int i = k, tot = sum[k]-sum[0]; i < n; i++) {
if (sum[i+1]-sum[i+1-k] > tot) {
posLeft[i] = i+1-k;
tot = sum[i+1]-sum[i+1-k];
}
else
posLeft[i] = posLeft[i-1];
}
// DP for starting index of the right max sum interval
// caution: the condition is ">= tot" for right interval, and "> tot" for left interval
posRight[n-k] = n-k;
for (int i = n-k-1, tot = sum[n]-sum[n-k]; i >= 0; i--) {
if (sum[i+k]-sum[i] >= tot) {
posRight[i] = i;
tot = sum[i+k]-sum[i];
}
else
posRight[i] = posRight[i+1];
}
// test all possible middle interval
for (int i = k; i <= n-2*k; i++) {
int l = posLeft[i-1], r = posRight[i+k];
int tot = (sum[i+k]-sum[i]) + (sum[l+k]-sum[l]) + (sum[r+k]-sum[r]);
if (tot > maxsum) {
maxsum = tot;
ans[0] = l; ans[1] = i; ans[2] = r;
}
}
return ans;
}
}
Python:
class Solution(object):
def maxSumOfThreeSubarrays(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
n = len(nums)
accu = [0]
for num in nums:
accu.append(accu[-1]+num) left_pos = [0] * n
total = accu[k]-accu[0]
for i in xrange(k, n):
if accu[i+1]-accu[i+1-k] > total:
left_pos[i] = i+1-k
total = accu[i+1]-accu[i+1-k]
else:
left_pos[i] = left_pos[i-1] right_pos = [n-k] * n
total = accu[n]-accu[n-k]
for i in reversed(xrange(n-k)):
if accu[i+k]-accu[i] > total:
right_pos[i] = i;
total = accu[i+k]-accu[i]
else:
right_pos[i] = right_pos[i+1] result, max_sum = [], 0
for i in xrange(k, n-2*k+1):
left, right = left_pos[i-1], right_pos[i+k]
total = (accu[i+k]-accu[i]) + \
(accu[left+k]-accu[left]) + \
(accu[right+k]-accu[right])
if total > max_sum:
max_sum = total
result = [left, i, right]
return result
C++:
class Solution {
public:
vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {
int n = nums.size(), maxsum = 0;
vector<int> sum = {0}, posLeft(n, 0), posRight(n, n-k), ans(3, 0);
for (int i:nums) sum.push_back(sum.back()+i);
// DP for starting index of the left max sum interval
for (int i = k, tot = sum[k]-sum[0]; i < n; i++) {
if (sum[i+1]-sum[i+1-k] > tot) {
posLeft[i] = i+1-k;
tot = sum[i+1]-sum[i+1-k];
}
else
posLeft[i] = posLeft[i-1];
}
// DP for starting index of the right max sum interval
// caution: the condition is ">= tot" for right interval, and "> tot" for left interval
for (int i = n-k-1, tot = sum[n]-sum[n-k]; i >= 0; i--) {
if (sum[i+k]-sum[i] >= tot) {
posRight[i] = i;
tot = sum[i+k]-sum[i];
}
else
posRight[i] = posRight[i+1];
}
// test all possible middle interval
for (int i = k; i <= n-2*k; i++) {
int l = posLeft[i-1], r = posRight[i+k];
int tot = (sum[i+k]-sum[i]) + (sum[l+k]-sum[l]) + (sum[r+k]-sum[r]);
if (tot > maxsum) {
maxsum = tot;
ans = {l, i, r};
}
}
return ans;
}
};
类似题目:
[LeetCode] 123. Best Time to Buy and Sell Stock III 买卖股票的最佳时间 III
All LeetCode Questions List 题目汇总
[LeetCode] 689. Maximum Sum of 3 Non-Overlapping Subarrays 三个非重叠子数组的最大和的更多相关文章
- [leetcode]689. Maximum Sum of 3 Non-Overlapping Subarrays三个非重叠子数组的最大和
In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. E ...
- [LeetCode] Maximum Sum of 3 Non-Overlapping Subarrays 三个非重叠子数组的最大和
In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. E ...
- Java实现 LeetCode 689 三个无重叠子数组的最大和(换方向筛选)
689. 三个无重叠子数组的最大和 给定数组 nums 由正整数组成,找到三个互不重叠的子数组的最大和. 每个子数组的长度为k,我们要使这3*k个项的和最大化. 返回每个区间起始索引的列表(索引从 0 ...
- [Swift]LeetCode689. 三个无重叠子数组的最大和 | Maximum Sum of 3 Non-Overlapping Subarrays
In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. E ...
- [Swift]LeetCode1031. 两个非重叠子数组的最大和 | Maximum Sum of Two Non-Overlapping Subarrays
Given an array A of non-negative integers, return the maximum sum of elements in two non-overlapping ...
- LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays
原题链接在这里:https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/ 题目: In a given arr ...
- [LeetCode] 918. Maximum Sum Circular Subarray 环形子数组的最大和
Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty ...
- leetcode面试题42. 连续子数组的最大和
总结一道leetcode上的高频题,反反复复遇到了好多次,特别适合作为一道动态规划入门题,本文将详细的从读题开始,介绍解题思路. 题目描述示例动态规划分析代码结果 题目 面试题42. 连续子数 ...
- 【LeetCode】689. Maximum Sum of 3 Non-Overlapping Subarrays 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/maximum- ...
随机推荐
- Python使用request包请求网页乱码解决方法
使用requests请求网页时,返回的页面信息有时是乱码,如下代码 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) App ...
- Multi-Task Feature Learning for Knowledge Graph Enhanced Recommendation(知识图谱)
知识图谱(Knowledge Graph,KG)可以理解成一个知识库,用来存储实体与实体之间的关系.知识图谱可以为机器学习算法提供更多的信息,帮助模型更好地完成任务. 在推荐算法中融入电影的知识图谱, ...
- 云服务器CentOS7.4下搭建GitLab
一.Git.GitHub.GitLab的区别 Git是版本控制系统,Github是在线的基于Git的代码托管服务. GitHub是2008年由Ruby on Rails编写而成.GitHub同时提供付 ...
- 关于jsp页面中name=“username”与name=“username ”的区别
我们可以仔细的观察一下,上面的name属性都等于username,但是确实存在大同小异的差距,为什么这样说呢,因为,第二个比第一个多了一个空格,在jsp中,我曾经遇到过一个情况就是两个单选按钮用同一个 ...
- 08.vue-router动态路由匹配
动态匹配路由的基本用法 思考: <!-有如下3个路由链接.-> <router-link to="/user/1">User1</router-lin ...
- 转发: JS中的call()和apply()方法和区别 --小白变色记
一.方法定义: apply:调用一个对象的一个方法,用另一个对象替换当前对象.例如:B.apply(A, arguments);即A对象应用B对象的方法. call:调用一个对象的一个方法,用另一个对 ...
- zeebe 0.20.0 发布生产可用了!
一个比较好消息,来自camunda zeebe 团队的消息,zeebe 0.20.0 发布,终于可以生产可用了 如果关注了官方的声明的话,同时团队也出了一个自己的许可协议,但是和大部分当前的开源 产品 ...
- 转载:Databricks孟祥瑞:ALS 在 Spark MLlib 中的实现
Databricks孟祥瑞:ALS 在 Spark MLlib 中的实现 发表于2015-05-07 21:58| 10255次阅读| 来源<程序员>电子刊| 9 条评论| 作者孟祥瑞 大 ...
- 「ZJOI2019」Minmax搜索
传送门 Solution 叶子节点的变化区间是连续的,可得知非叶子节点的权值变化区间也是连续的 由此可知,\(W\)的变化值的可行域也是连续的,所以只需要看它能否变为\(W+1\)或\(W-1\) 对 ...
- 第06组 Alpha冲刺(2/4)
队名:福大帮 组长博客链接:https://www.cnblogs.com/mhq-mhq/p/11885037.html 作业博客 :https://edu.cnblogs.com/campus/f ...