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.

click to show more practice.

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.

 1 public class Solution {
 2     public int maxSubArray(int[] A) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         int sum = 0;
 5         int max = Integer.MIN_VALUE;
 6         if(A == null) return 0;
 7         int len = A.length;
 8         if(len == 0) return 0;
 9         for(int i = 0; i < len; i ++)
10         {
11             sum += A[i];
12             if(sum > max) max = sum;
13             if(sum < 0) sum = 0;
14         }
15         return max;
16     }
17 }

这一题做了太多次了。。。。

 

第三遍:

 1 public class Solution {
 2     public int maxSubArray(int[] A) {
 3         if(A == null || A.length == 0) return 0;
 4         int pre = 0, sum = 0, max = Integer.MIN_VALUE;
 5         while(pre < A.length){
 6             if(sum >= 0){
 7                 sum += A[pre ++];
 8                 max = max > sum ? max : sum;
 9             }else
10                 sum = 0;
11         }
12         return max;
13     }
14 }

 

posted on 2013-10-04 12:17  Step-BY-Step  阅读(107)  评论(0编辑  收藏  举报

导航