最大子序列(java版)
1 package com.algorithm.test; 2 /** 3 * 最大子序列 4 * @author LiFen 5 * 6 */ 7 public class LargestSubsequence { 8 public static void main(String[] args) { 9 int[] arr = {4,-3,5,-2,-1,2,6,-2}; 10 System.out.println(maxSubSum(arr)); 11 12 System.out.println(maxSumRec(arr, 0, arr.length - 1)); 13 14 System.out.println(maxSubSum2(arr)); 15 } 16 17 /* 18 * 时间复杂度O(N*N) 19 */ 20 public static int maxSubSum(int [] a) { 21 int maxSum = 0; 22 23 for(int i = 0; i < a.length; i++) { 24 int thisSum = 0; 25 for(int j = 0; j < a.length; j++) { 26 27 thisSum += a[j]; 28 29 if(thisSum > maxSum) 30 maxSum = thisSum; 31 } 32 } 33 return maxSum; 34 } 35 /* 36 * 递归 37 * 时间复杂度O(N logN) 38 */ 39 public static int maxSumRec(int [] a, int left, int right) { 40 if(left == right) { 41 if(a[left] > 0) 42 return a[left]; 43 else return 0; 44 } 45 46 int center = (left + right) / 2; 47 int maxLeftSum = maxSumRec(a, left, center); 48 int maxRightSum = maxSumRec(a, center + 1, right); 49 50 int maxLeftBorderSum = 0,leftBorderSum = 0; 51 for(int i = center; i >= left; i--) { 52 leftBorderSum += a[i]; 53 if(leftBorderSum > maxLeftBorderSum) 54 maxLeftBorderSum = leftBorderSum; 55 } 56 57 int maxRightBorderSum = 0, rightBoderSum = 0; 58 for(int i = center + 1; i <= right; i++) { 59 rightBoderSum += a[i]; 60 if(rightBoderSum > maxRightBorderSum) 61 maxRightBorderSum = rightBoderSum; 62 } 63 return Math.max(Math.max(maxLeftSum, maxRightSum),maxLeftBorderSum + maxRightBorderSum); 64 } 65 /* 66 * 联机算法 67 * 快 68 */ 69 public static int maxSubSum2(int [] a) { 70 int maxSum = 0, thisSum = 0; 71 72 for(int i = 0; i < a.length; i++) { 73 thisSum += a[i]; 74 75 if(thisSum > maxSum) { 76 maxSum = thisSum; 77 }else if(thisSum < 0){ 78 thisSum = 0; 79 } 80 } 81 return maxSum; 82 } 83 }