A minimal segment of the summation algorithm analysis

#include <iostream>
using namespace std;

MinSubSum int (int n, int a [], int & Best int & bestj) {
    int sum =0,b=0;
    int j;
    for(j=0;j<n;j++){
        b+=a[j];
        if(b>0){
            b=0;
            besti = j + 1; // Once b> 0, discards previous results, the position j of the next record
            bestj=j+1;
        }
        if(b<sum){
            sum=b;
            bestj = j; // bestj follow sum update update
        }
    }
    return sum;
}

int main () {
    int best, bestj;
    best = bestj = 0;
    int a[5]={2,-19,13,-20,-1};
    cout << "and minimum field:" << MinSubSum (5, a, besti, bestj) << endl;
    cout << "starting position:" << besti << endl;
    cout << "end position:" << bestj << endl;
}

 

 

 

Guess you like

Origin www.cnblogs.com/khnl/p/11683704.html