找到最大连续子序列和的开始和结束

时间:2016-04-28 17:33:56

标签: c++ max sequences

这是我找到最大的最大连续子序列和的程序。我能够计算总和。如何修改此代码以找到此最大子序列和的起始和结束索引?

int maxSubArraySum(int a[], int size)
{
   int final_max = 0, curr_max = 0;
   for (int i = 0; i < size; i++)
   {
       curr_max = curr_max + a[i];
       if (curr_max < 0)
           curr_max = 0;

       else if (final_max < curr_max)
           final_max = curr_max;
   }
   return final_max;
}

1 个答案:

答案 0 :(得分:0)

您只需记住开始总和的指数以及总和结束的位置。

struct SumAndRange{
    int sum;
    int start;
    int stop;
    SumAndRange() : sum(0),start(0),stop(0) {}
};

SumAndRange maxSubArraySum(int a[], int size) {
    SumAndRange curr;                // we will start with the sum of the first element
    SumAndRange final;
    for (int i = 0; i < size; i++) {
        curr.sum = curr.sum + a[i];
        if (curr.sum < 0) {          // if we reset the sum it will
            curr.sum = 0;            // start with the next index
            curr.start = i+1;     
            curr.stop = i+1;         // ...and we also handle the case of
                                     // the sum is only one element

        } else {                     // otherwise the sum continues with
            curr.stop = i;           // this index
            if (final.sum < curr.sum) { final = curr; }
        } 
    }
    return final;
}   

int main() {
    int a[] = { 2,-6,7,-3,12};
    SumAndRange sar = maxSubArraySum(a,5);
    std::cout << sar.sum << " " << sar.start << " " << sar.stop << std::endl;
    return 0;
}