Find Max Subarray

来源:互联网 发布:1.12魔兽世界数据库 编辑:程序博客网 时间:2024/06/09 18:21
//one dimension dp  public int maxSubArray(int[] A) {      // Start typing your Java solution below      // DO NOT write main() function      int max = 0;      int result = Integer.MIN_VALUE;      for(int i = 0; i < A.length; i++) {          max += A[i];          result = Math.max(max, result);          max = max > 0 ? max : 0;      }      return result;  }  public int[] maxSubArray(int[] A) {int max = 0;int result = Integer.MIN_VALUE;//if a[1] is negative but the largest in the array, then print a[1]int start = 0;int end = 0;int tmp = 0;for(int i = 0; i < A.length; i++) {max += A[i];if(max > result) {end = i;start = tmp;result = max;}if(max < 0) {tmp = i + 1;}}if(end - start + 1 > 0) {int[] a = new int[end - start + 1];for(int i = 0; i < a.length; i++){a[i] = A[start + i];}return a;}return null;}

原创粉丝点击