lintcode-medium-Maximum Subarray II
2016-03-30 13:04
381 查看
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.
Notice
The subarray should contain at least one number
Example
For given
Challenge
Can you do it in time complexity O(n) ?
The number in each subarray should be contiguous.
Return the largest sum.
Notice
The subarray should contain at least one number
Example
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.
Challenge
Can you do it in time complexity O(n) ?
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 if(nums == null || nums.size() == 0) return 0; int size = nums.size(); int sum = nums.get(0); int[] l2r = new int[size]; int[] r2l = new int[size]; l2r[0] = nums.get(0); r2l[size - 1] = nums.get(size - 1); for(int i = 1; i < size; i++){ if(sum < 0) sum = 0; sum += nums.get(i); if(sum > l2r[i - 1]) l2r[i] = sum; else l2r[i] = l2r[i - 1]; } sum = nums.get(size - 1); for(int i = size - 2; i >= 0; i--){ if(sum < 0) sum = 0; sum += nums.get(i); if(sum > r2l[i + 1]) r2l[i] = sum; else r2l[i] = r2l[i + 1]; } int result = Integer.MIN_VALUE; for(int i = 0; i < size - 1; i++) result = Math.max(result, l2r[i] + r2l[i + 1]); return result; } }
相关文章推荐
- 某基础的组合问题
- MySQL数据库主主
- Winform以任意角度旋转PictureBox中的图片的方法
- 链表的增删、查找以及逆序
- paddinglfet和marginleft区别
- 用Xocde搭建python开发环境
- 短信问题排查
- 十分钟搞懂什么是CGI(转)
- 迷宫的最短路径
- linux 命令快捷键(xshell环境下)
- 使用Android Studio的Live Templates——实现用少量的代码写出更多的代码
- HTTP真的很简单(转)
- Debug Assertion Failed Expression: _pFirstBlock==pHead
- 数据库并发学习总结
- LNMP配置
- ODS与EDW的区别
- bzoj3551 Peaks加强版 最小生成树&主席树
- LA4621 Cav
- iOS9 访问通讯录
- oracle之spool详细使用总结(转)