DP動態規劃算法

最大連續子序列之和

 給定整數A1,A2,A3,...,An(可能爲負整數),求最大的連續子序列和。如果所有數是負數,則和是零。
 例如:{-2,11,-4,13,-5,2} 答案是20,序列項從第2項到第4項。
 此題很多解法,現討論4種解法。第1種是簡單窮舉搜索算法,效率特別低。第2種算法是第一種算法的改進,簡單觀察完成。第3種算法非常高效,但不簡單,複雜度是線性的O(n)。第4種算法複雜度是O(N log N)

 

  1. public static int maxSumRec(int[] a, int left, int right)  
  2.     {  
  3.         int maxLeftBorderSum = 0, maxRightBorderSum = 0;  
  4.         int leftBorderSum = 0, rightBorderSum = 0;  
  5.         int center = (left + right) / 2;  
  6.   
  7.         if (left == right)// 基本的情況,只有一種元素  
  8.         {  
  9.             return a[left] > 0 ? a[left] : 0;  
  10.         }  
  11.   
  12.         int maxLeftSum = maxSumRec(a, left, center);// 執行遞歸調用,計算左半部最大和  
  13.         int maxRightSum = maxSumRec(a, center + 1, right);// 執行遞歸調用,計算右半部分最大和  
  14.   
  15.         for (int i = center; i >= left; i--)// 計算包括中心邊界的左最大和  
  16.         {  
  17.             leftBorderSum += a[i];  
  18.             if (leftBorderSum > maxLeftBorderSum)  
  19.                 maxLeftBorderSum = leftBorderSum;  
  20.         }  
  21.   
  22.         for (int i = center + 1; i <= right; i++)// 計算包括中心邊界的右最大和  
  23.         {  
  24.             rightBorderSum += a[i];  
  25.             if (rightBorderSum > maxRightBorderSum)  
  26.                 maxRightBorderSum = rightBorderSum;  
  27.         }  
  28.         return max3(maxLeftSum, maxRightSum, maxLeftBorderSum  
  29.                 + maxRightBorderSum);  
  30.     }  
  31.   
  32.     public static int max3(int maxLeftSum, int maxRightSum, int maxSum)//計算3個數最大的  
  33.     {  
  34.         return maxLeftSum > maxRightSum ? (maxLeftSum > maxSum ? maxLeftSum  
  35.                 : maxSum) : (maxRightSum > maxSum ? maxRightSum : maxSum);  
  36.     }  
  37.   
  38.     public static int maxSubsequenceSum(int[] a)  
  39.     {  
  40.         return a.length > 0 ? maxSumRec(a, 0, a.length - 1) : 0;  
  41.     }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章