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. django项目中使用bootstrap插件的分页功能。

    官网下载bootstrap插件放到项目中的static文件中 路由 path('blog-fullwidth/', login.fullwidth,name='fullwidth'), 前端页面引入 ...

  2. Codeforces G. Nick and Array(贪心)

    题目描述: Nick had received an awesome array of integers a=[a1,a2,…,an] as a gift for his 5 birthday fro ...

  3. python笔记42-http请求命令行工具(httpie)

    前言 通常我们需要快速的测试某个接口通不通,一般linux上用curl去发http请求,但是这个命令行工具语法有点复杂了,不够直观. python有一个给人类使用的requests库,非常的简单方便. ...

  4. hiveSQL常用日期函数

    注意 MM,DD,MO,TU 等要大写 Hive 可以在 where 条件中使用 case when 已知日期 要求日期 语句 结果 本周任意一天 本周一 select date_sub(next_d ...

  5. C# 跨线程对控件赋值

    第一种 跨线程对控件赋值 private void button2_Click(object sender, EventArgs e) { Thread thread1 = new Thread(ne ...

  6. Direction of Arrival Based Spatial Covariance Model for Blind Sound Source Separation

    基于信号协方差模型DOA的盲声源分离[1]. 在此基础上,作者团队于2018年又发布了一篇文章,采用分级和时间差的空间协方差模型及非负矩阵分解的多通道盲声源分离[2]. 摘要 本文通过对短时傅立叶变换 ...

  7. fibnacci数列递归实现

    斐波那契数列 Fibonacci sequence又称黄金分割数列.因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为"兔子数列" ...

  8. 异常过滤器的好坏(CLR)

    为什么有些语言支持它们而另一些不支持呢?把它们加到我的新语言里是个好主意吗?我应该什么时候使用过滤器和catch/rethrow?就像很多事情一样,异常过滤器有好的一面也有坏的一面… 什么是异常过滤器 ...

  9. C++函数声明后面加throw()的作用

    原文地址:https://blog.csdn.net/to_baidu/article/details/53763683 C++里面为什么有时候在函数声明的时候在后面加throw()关键字? 解释: ...

  10. 2017.10.2 国庆清北 D2T1 (a*b)|x

    在电脑上后面仨点过不了,要用I64d,lld会炸.但是洛谷上要用lld,LINUX系统没有I64d /* 求一个数对满足 (a*b)|n,也就是求三个数 a*b*c=n,那么求1~n之间的,就是a*b ...