最大子序列和的线性时间算法

最大子系列和的线性时间算法

概述

求一个给定序列的最大子序列和,问题非常常用,下面给出一个线性时间算法。

代码

#include <iostream>
using namespace std;

/**
  * The max sub sequences problem. It is implemented by using on-line method.
  * The complexity of method is O(n), which is linear time. It is the most superior method.
  * @author Junpeng Zhu
  * @arr the parameter of array
  * @length the parameter of array length
*/
int maxSubSeqSum(int arr[], int length){
    int currentSum = 0;
    int maxSum = 0;
    for (int i = 0 ; i < length ; i++){
        currentSum += arr[i];
        if (currentSum > maxSum){
            maxSum = currentSum;
        }else if (currentSum < 0){
            currentSum = 0 ;
        }
    }
    return maxSum;
}


int main()
{
    int arr[] = {-1,3,-2,4,-6,1,6,-1};
    int length = sizeof(arr)/sizeof(arr[0]);
    int max = maxSubSeqSum(arr,length);
    cout << max << endl;
    return 0;
}

zuida uida zuida zuida 最大子序列和

猜你喜欢

转载自blog.csdn.net/jpzhu16/article/details/80407474
今日推荐