13.2 Maximum Subarray

来源:互联网 发布:淘宝重复铺货怎么处罚 编辑:程序博客网 时间:2024/06/08 19:37

Link: https://oj.leetcode.com/problems/maximum-subarray/

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6

Approach I:Kadane's Algorithm

Time: O(n), Space: O(1)

Note: By initializing local and global to A[0], not 0, we can deal with the scenario when A has all negative elements. 

http://blog.csdn.net/linhuanmars/article/details/21314059

public class Solution {    public int maxSubArray(int[] A) {        int local = A[0];//Initialized to A[0], not 0        int global = A[0];//Initialized to A[0], not 0        for(int i = 1; i < A.length; i++){            local = Math.max(A[i], local+A[i]);            global = Math.max(global, local);        }        return global;    }}


Approach II: Divide and Conquer  //don't understand (can't draw flow)

Time: O(nlogn), 

public class Solution {    public int maxSubArray(int[] A) {        //my 2nd attempt for the 2nd solution: divide-and-conquer after seeing the answer        int left = 0;        int right = A.length - 1;        int max = Integer.MIN_VALUE;        return maxSubArray(A, left, right, max);          }         public int maxSubArray(int[] A, int left, int right, int max) {         if(left > right){            return Integer.MIN_VALUE;         }         int mid = (left + right)/2;         int leftMax = maxSubArray(A, left, mid-1, max);         max = Math.max(max, leftMax);         int rightMax = maxSubArray(A, mid+1, right, max);         max = Math.max(max, rightMax);         //if the maxSubArray goes across the mid         int lSum = 0;         int maxLSum = 0;         for(int i = mid-1; i>=left;i-- ){              lSum += A[i];              if(lSum > maxLSum){                  maxLSum = lSum;              }         }         int rSum = 0;         int maxRSum = 0;         for(int i = mid+1; i<=right;i++){              rSum += A[i];              if(rSum > maxRSum){                  maxRSum = rSum;              }         }         return Math.max(max, maxLSum+maxRSum+A[mid]);         }}




相关题目:Jump Game (Approach I)
0 0