Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.

For given [1, 3, -1, 2, -1, 2], the two subarrays are [1, 3] and [2, -1, 2] or [1, 3, -1, 2] and [2], they both have the largest sum 7.

思路:遍历每一个分割线,分别求分割线左边的最大子数组和分割线右边的最大子数组。为了实现O(n) 的时间复杂度,可以创建left[] 、right[] 数组,其中left[i] 表示从0 ~ i 的数组的子数组最大值,right[j] 表示nums.length - 1 ~ j 的数组的子数组最大值。

 public class Solution {
/**
* @param nums: A list of integers
* @return: An integer denotes the sum of max two non-overlapping subarrays
*/
public int maxTwoSubArrays(ArrayList<Integer> nums) {
if (nums == null || nums.size() == 0) {
return 0;
}
int[] left = new int[nums.size()];
int[] right = new int[nums.size()];
int sum = 0, max = Integer.MIN_VALUE;
for (int i = 0; i < nums.size(); i++) {
sum = sum + nums.get(i);
max = Math.max(max, sum);
sum = Math.max(sum, 0);
left[i] = max;
}
sum = 0;
max = Integer.MIN_VALUE;
for (int i = nums.size() - 1; i >= 0; i--) {
sum = sum + nums.get(i);
max = Math.max(max, sum);
sum = Math.max(sum, 0);
right[i] = max;
}
max = Integer.MIN_VALUE;
for (int i = 0; i < nums.size() - 1; i++) {
max = Math.max(left[i] + right[i + 1], max);
}
return max;
}
}
 public class Solution {
/**
* @param nums: A list of integers
* @return: An integer denotes the sum of max two non-overlapping subarrays
*/
public int maxTwoSubArrays(ArrayList<Integer> nums) {
// write your code
int size = nums.size();
int[] left = new int[size];
int[] right = new int[size];
int sum = 0;
int minSum = 0;
int max = Integer.MIN_VALUE;
for(int i = 0; i < size; i++){
sum += nums.get(i);
max = Math.max(max, sum - minSum);
minSum = Math.min(sum, minSum);
left[i] = max;
}
sum = 0;
minSum = 0;
max = Integer.MIN_VALUE;
for(int i = size - 1; i >= 0; i--){
sum += nums.get(i);
max = Math.max(max, sum - minSum);
minSum = Math.min(sum, minSum);
right[i] = max;
}
max = Integer.MIN_VALUE;
for(int i = 0; i < size - 1; i++){
max = Math.max(max, left[i] + right[i + 1]);
}
return max;
}
}

最新文章

  1. table td 文字超出显示省略号
  2. 利用IIS导出,导入快速部署 web站点
  3. matlab实现感知机算法--统计学习小灶
  4. iOS-动态调整UITableViewCell的高度
  5. Ubuntu 出现 apt-get问题的解决方法
  6. Socket.io在线聊天室
  7. 高级UIKit-03(NSFileManager、NSFileHandle)
  8. Xamarin C# Android for Visual Studio 平台安装
  9. php基础(六)Include
  10. C# groupby 应用小技巧
  11. 3.2.2 SpringMVC配置式开发
  12. 网络知识--OSI七层网络与TCP/IP五层网络架构及二层/三层网络
  13. emr hadoop 参数调优
  14. C# MVC+EF—WebApi
  15. LeetCode119.杨辉三角II
  16. Sitecore CMS中配置项目图标
  17. Ubuntu下安装JDK图文教程详解 jdk-java6-30 .bin 的处理方法
  18. swift -2018 - 创建PCH文件
  19. verilog中的多维数组
  20. BZOJ 2821作诗(Poetize) 分块

热门文章

  1. Nginx07---反向代理
  2. Eclipse控制台不限日志行数
  3. STM32之SPI时钟相位选择
  4. 又是a+b
  5. 剑指offer59:按之字形顺序打印二叉树:[[1], [3,2], [4,5,6,7]]
  6. 小游戏UFO Fled
  7. springboot整合druid、mybatis
  8. url格式化函数http_build_query() 和parse_str() 函数
  9. 基于re模块的计算器
  10. TR-FS00会计科目创建GL_ACCT_MASTER_SAVE