Maximum Subarray - LeetCode

来源:互联网 发布:json字符串解析 编辑:程序博客网 时间:2024/06/05 18:39

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.

要注意这里返回条件的界定和设定,十分容易出错!!!

这里的报错和我的Eclipse上显示的不一样,我认为我的方法应该是AC的, 不知道是什么bug。

Input:[-1,-2]Output:-2Expected:-1

public class Solution { public int maxSubArray(int[] A) {         int max = -9999;     int maxindex = 0;     int min = 9999;     int minindex = 0;     int sum = 0;     int[] B = A;          for(int i = 0; i < A.length; i++){         sum = sum + A[i];         B[i] = sum;         //System.out.println(B[i]);     }     for(int i = 0; i < A.length; i++){                  maxindex = (B[i] > max)? i:maxindex;         max = Math.max(B[i], max);      //   System.out.println(maxindex);     }     for(int i = 0; i < A.length; i++){         minindex = (B[i] < min)? i:minindex;         min = Math.min(B[i], min);     }    // System.out.println(maxindex);   //  System.out.println(minindex);     if(maxindex == minindex)     return A[maxindex];     else{         if(maxindex > minindex){             return B[maxindex] - B[minindex];         }         else             return - B[maxindex] + B[minindex];     }          }}

给一个我喜欢的AC方法:
public class Solution {public int maxSubArray(int[] A) {int max = A[0];int[] sum = new int[A.length];sum[0] = A[0]; for (int i = 1; i < A.length; i++) {sum[i] = Math.max(A[i], sum[i - 1] + A[i]);max = Math.max(max, sum[i]);} return max;}}


0 0