1. 程式人生 > >java求連續子陣列的和最大

java求連續子陣列的和最大

 1 package com.island.info;
 2 /** 3  * <p>Title: TestMaxArray.java</p>
 4  * <p>Description: 分治法求解連續和最大</p>
 5  * @date 2014-3-05
 6  *
 7 */
 8  
 9 public class MaxSub {
10         static int arr[] = {4,-3,5,-2,-1,2,6,-2};    //也可以隨機生成11         public static void main(String args[]){
12             System.out.println(max(arr));
13
         }
14  
15         //包裝函式16         public static int max(final int[] arr){
17             System.out.println("(1)*****arr.length-1----------------->:"+ (arr.length-1));
18             return max(arr,0,arr.length-1);
19         }
20  
21         //核心程式碼:遞迴呼叫max()22         public static int max(final int
[] arr,int leftIndex, int rightIndex){
23             System.out.println("(2)*****leftIndex--------rightIndex--->:"+leftIndex+"|***************|"+rightIndex);
24             int sum = 0,leftHalfMax = 0, rightHalfMax = 0;
25             if (rightIndex-leftIndex==0){
26                 return arr[rightIndex];
27
             } else {
28                 int center = (leftIndex+rightIndex)/2;//2分查詢中間節點29                 int maxLeft = max(arr,leftIndex,center);//左邊最大的30                 int maxRight = max(arr,center+1,rightIndex);//右邊最大的
31 //以下是查詢跨越中間點的最大子序列
32 //從中點到左側:33                 for (int i=center;i>=leftIndex;--i){
34                     sum+=arr[i];
35                     if (sum>leftHalfMax){
36                         leftHalfMax = sum;
37                     }
38                 }
39                 System.out.println("左邊的sum----------->:"+sum);
40                 sum=0;
41                 //從中點到右側42                 for (int i=center+1;i<=rightIndex;++i){
43                     sum+=arr[i];
44                     if (sum>rightHalfMax){
45                         rightHalfMax = sum;
46                     }
47                 }
48                 System.out.println("右邊的sum----------->:"+sum);
49                 return max(maxLeft,maxRight,leftHalfMax+rightHalfMax);
50             }
51         }
52  
53         //三者取最大值54         public static int max(int a,int b,int c){
55             return a>b?(a>c?a:c):(b>c?b:c);
56         }
57     }