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. 【后缀表达式求解】No.3.栈-evaluate-reverse-polish-notation题解(Java版)

    牛客网的题目链接 题目描述 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid opera ...

  2. linux下写tomcat启动,重启的脚本

    启动: #bash/bin cd /finance/ LANG="en_US.UTF-8" export LANG /finance/tomcat8-finance/bin/cat ...

  3. MapReduce如何解决数据倾斜?

    数据倾斜是日常大数据查询中隐形的一个BUG,遇不到它时你觉得数据倾斜也就是书本博客上的一个无病呻吟的偶然案例,但当你遇到它是你就会懊悔当初怎么不多了解一下这个赫赫有名的事故. https://www. ...

  4. 分享STM32 FLASH 擦除(以及防止误擦除程序代码)、写入

    编译环境:我用的是(Keil)MDK4.7.2   stm32库版本:我用的是3.5.0一.本文不对FLASH的基础知识做详细的介绍,不懂得地方请查阅有关资料. 对STM32 内部FLASH进行编程操 ...

  5. git工具免密拉取、推送

    很苦恼每次都要配置明文密码才能正常工作 其实也可以配置成非明文 打开控制面板 →用户账号 管理 Windows凭证 对应修改响应网址即可  

  6. Django ContentTypes框架使用场景

    Django contenttypes是一个非常有用的框架,主要用来创建模型间的通用关系(generic relation).不过由于其非常抽象, 理解起来并不容易.当你创建一个django项目的时候 ...

  7. Pivotal Greenplum 6.0 新特性介绍

    Pivotal Greenplum 6.0 新特性介绍   在1月12日举办的Greenplum开源有道智数未来技术研讨会上,Pivotal中国研发中心Greenplum 产品经理李阳向大家介绍了Pi ...

  8. S1_搭建分布式OpenStack集群_11 虚拟机创建

    一.创建网络环境环境变量生效一下创建一个网络:# openstack network create --share --external \--provider-physical-network ph ...

  9. java解决大文件断点续传

    第一点:Java代码实现文件上传 FormFile file = manform.getFile(); String newfileName = null; String newpathname =  ...

  10. Linux 系统管理——文件系统与LVM、磁盘配额实例

    1.为主机增加80G SCSI 接口硬盘 2.划分三个各20G的主分区 3.将三个主分区转换为物理卷(pvcreate),扫描系统中的物理卷 4.使用两个物理卷创建卷组,名字为myvg,查看卷组大小 ...