• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Lintcode: 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.

Note
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) ?

思路:把数组分成两部分,可以从i和i+1(0<=  i < len-1)之间分开,a[0, i] a[i+1, len-1],然后分别求两个子数组中的最大子段和,然后求和的最大值即可。

 1 public class Solution {
 2     /**
 3      * @param nums: A list of integers
 4      * @return: An integer denotes the sum of max two non-overlapping subarrays
 5      */
 6     public int maxTwoSubArrays(ArrayList<Integer> nums) {
 7         // write your code
 8         if (nums==null || nums.size()==0) return 0;
 9         int len = nums.size();
10         int lLocal = nums.get(0);
11         int[] lGlobal = new int[len];
12         lGlobal[0] = lLocal;
13         for (int i=1; i<len; i++) {
14             lLocal = Math.max(lLocal+nums.get(i), nums.get(i));
15             lGlobal[i] = Math.max(lLocal, lGlobal[i-1]);
16         }
17         
18         int rLocal = nums.get(len-1);
19         int[] rGlobal = new int[len];
20         rGlobal[len-1] = rLocal;
21         for (int i=len-2; i>=0; i--) {
22             rLocal = Math.max(rLocal+nums.get(i), nums.get(i));
23             rGlobal[i] = Math.max(rLocal, rGlobal[i+1]);
24         }
25         
26         int res = Integer.MIN_VALUE;
27         for (int k=0; k<len-1; k++) {
28             if (res < lGlobal[k]+rGlobal[k+1]) 
29                 res = lGlobal[k] + rGlobal[k+1];
30         }
31         return res;
32     }
33 }

 

posted @ 2015-03-14 05:49  neverlandly  阅读(476)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3