1. 程式人生 > >求最大子列和

求最大子列和

int MaxSubSeqSum(int arr[], int n) {
      int currentSum, maxSum;
      currentSum = maxSum = 0;
      for(int i=0; i<n; i++) {
          currentSum += arr[i];  /* 向右累加 */
          if(currentSum > maxSum) {  /* 發現更大值 更新最大值 */
              maxSum = currentSum;
          }else if(currentSum < 0){  /* 如果當前子列為負 捨棄 置零 */
              currentSum = 0;
         }
     }
     return maxSum;
 }