Search code examples
c++maxsequences

Find the beginning and end of largest contiguous sub-sequence sum


This is my program to find the largest largest contiguous sub-sequence sum. I'm able to calculate the sum.How can this code be modified to find the beginning and end index of this max sub-sequence sum ?

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;
}

Solution

  • You just have to remember the index where you start the sum and where the sum ends.

    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;
    }