LeetCode - 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.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Solution:
 1 public class Solution {
 2     public int maxSum(int[] a, int left, int right){
 3         if(left == right) return a[left];
 4         int mid = (left + right) / 2;
 5         int leftSum = maxSum(a, left, mid);
 6         int rightSum = maxSum(a, mid+1, right);
 7         
 8         int tmpLeftSum = 0;
 9         int tmpRightSum = 0;
10         int s1 = Integer.MIN_VALUE, s2 = Integer.MIN_VALUE;
11         for(int i = mid; i >= left; i--){
12             tmpLeftSum += a[i];
13             s1 = Math.max(s1, tmpLeftSum); 
14         }
15         for(int i = mid+1; i <= right; i++){
16             tmpRightSum += a[i];
17             s2 = Math.max(s2, tmpRightSum);
18         }
19         
20         return Math.max(Math.max(leftSum, rightSum), s1+s2);
21     }
22     
23     public int maxSum2(int[] A){
24         int len = A.length;
25         int ans = A[0];
26         int tmpSum = A[0];
27         for(int i = 1; i < len; i++){
28             if(tmpSum > 0){
29                 tmpSum = tmpSum + A[i];
30             }
31             else tmpSum = A[i];
32             ans = Math.max(ans, tmpSum);
33         }
34         return ans;
35     }
36     
37     public int maxSubArray(int[] A) {
38         // Start typing your Java solution below
39         // DO NOT write main() function
40         return maxSum(A, 0, A.length-1);
41         //return maxSum2(A);
42     }
43 }

 

posted @ 2013-01-27 11:46  cradle  阅读(549)  评论(0编辑  收藏  举报