zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    20201303 2019-2020-2 《Python程序设计》实验三报告
    20201303 2020-2021-2 《Python程序设计》实验二报告
    20201303张奕博 实验一 Python程序设计入门
    2020-2021-1博客汇总
    俄罗斯方块and四则运算实践
    python对于数据库的相关实践
    20201303获奖感言与学习体会
    openssl实践
    2021-2022 2113 2114信息安全导论 第五周总结
    第九章第十章
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4336963.html
Copyright © 2011-2022 走看看