lintcode-medium-Maximum Subarray II
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Maximum Subarray II相关的知识,希望对你有一定的参考价值。
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 [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; } }
以上是关于lintcode-medium-Maximum Subarray II的主要内容,如果未能解决你的问题,请参考以下文章
s-s-rS 报告 - 从没有 s-s-rS 服务器的 C# 导出
s-s-rS 报告需要在 s-s-rS 2008 (VS 2008) 中重用来自 s-s-rS 2005 (VS 2005) 的 rdl 文件