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 三个非重叠子数组的最大和的更多相关文章

  1. [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 ...

  2. [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 ...

  3. Java实现 LeetCode 689 三个无重叠子数组的最大和(换方向筛选)

    689. 三个无重叠子数组的最大和 给定数组 nums 由正整数组成,找到三个互不重叠的子数组的最大和. 每个子数组的长度为k,我们要使这3*k个项的和最大化. 返回每个区间起始索引的列表(索引从 0 ...

  4. [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 ...

  5. [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 ...

  6. LeetCode 689. Maximum Sum of 3 Non-Overlapping Subarrays

    原题链接在这里:https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/ 题目: In a given arr ...

  7. [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 ...

  8. leetcode面试题42. 连续子数组的最大和

      总结一道leetcode上的高频题,反反复复遇到了好多次,特别适合作为一道动态规划入门题,本文将详细的从读题开始,介绍解题思路. 题目描述示例动态规划分析代码结果 题目   面试题42. 连续子数 ...

  9. 【LeetCode】689. Maximum Sum of 3 Non-Overlapping Subarrays 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/maximum- ...

随机推荐

  1. 关于 ES5 & ES6 数组遍历的方法

    ES5 数组遍历方法 1.for 循环 , , , , ] ; i < arr.length; i++) { console.log(arr[i]) } 2.forEach , , , , ] ...

  2. 类型擦除对Java调用Kotlin的影响

    @JvmName: 扩展方法相关: 先来定义一个扩展方法: 好,接下来再来定义一个扩展函数: 此时报错了..看一下错误提示: 其中给的提示有点奇怪,第一个是很明显咱们的扩展函数木有接收参数嘛,为啥提示 ...

  3. JAVA项目部署(1)

    之前小菜觉得项目发布啊部署可难了,今个儿小菜接有幸触了一下java项目的打包和部署,没上手前觉得可高大上了,可难了,小菜这人就是做没做过的事前特别喜欢自己吓唬自己,这个习惯不好,得改!其实自己真正动手 ...

  4. SringBoot启动报日志配置错误-logback检测异常

    最近在启动项目的时候,报错,报错的原因是springBoot日志配置文件不对. 由于自己是刚接触springboot,是同事帮忙解决的,自己非常感谢! 先总结如下: 1.首先,找到logback-sp ...

  5. tensorflow API _ 4 (优化器配置)

    """Configures the optimizer used for training. Args: learning_rate: A scalar or `Tens ...

  6. Statistical Methods for Machine Learning

    机器学习中的统计学方法. 从机器学习的核心视角来看,优化(optimization)和统计(statistics)是其最最重要的两项支撑技术.统计的方法可以用来机器学习,比如:聚类.贝叶斯等等,当然机 ...

  7. (尚022)Vue案例_初始化显示(十分详细!!!)

    项目结构目录 所需资料: comment_page文件夹: ====================================================================== ...

  8. CF1172E Nauuo and ODT LCT

    自己独立想出来的,超级开心 一开始想的是对于每一个点分别算这个点对答案的贡献. 但是呢,我们发现由于每一条路径的贡献是该路径颜色种类数,而每个颜色可能出现多次,所以这样就特别不好算贡献. 那么,还是上 ...

  9. 将windbg与.dmp文件关联

    如果您厌倦了启动调试器.加载转储文件.设置sympath.加载扩展名等,这里有一个很好的方法,可以在.dmp文件的上下文菜单上获取“调试此转储文件”,并自动加载所有您喜欢的命令.首先创建一个包含以下内 ...

  10. windowns server 2008 r2 AD桌面文件重定向设置

    1.创建将要进行重定向的组(此处为chongdingxiangzu) 2.选择要重定向的用户,并将此用户加入到要重定向的组里 3.打开组策略管理,右击刚才用户所属的组织单位(OU)进行新建GPO(此处 ...