Search code examples
c++arrayskadanes-algorithm

Finding the contiguous sub array with max sum


here's my program to find the maximum sum of a sub array (contiguous) from a given array. it's very easy using kadane's algorithm.

#include <iostream>
#include <cstdio>

using namespace std;

int kadane(int a[], int n) {

    int max_ending_here = a[0], max_till_now = a[0];

    int _start = 0, _end;

    bool s=true;

    for (int i = 1; i < n; ++i)
    {
        max_ending_here = max(a[i], max_ending_here + a[i]);

        if(max_ending_here + a[i] > a[i] && s==false) _start = i, s=true;

        max_till_now = max(max_ending_here, max_till_now);

        if(max_ending_here + a[i] < a[i] && s==true) _end=i-1,s=false;
    }

     printf("S = %d , E = %d\n",_start,_end);

    return max_till_now;
}

int main(int argc, char const *argv[])
{
    //int a[10] = {1,-3,2,-5,7,6,-1,-4,11,-23};
    int a[6] = {-8,-1,-1,-1,-1,-5};
    int m = kadane(a, 6);
    printf("%d\n",m);
    return 0;
}

but i also want to find the start and end position of that contiguous sub-array which has the max sum. i tried adding couple of lines in above program to do that, but it didn't work. so my question is how can i get the start and end positions of that sub-array having max sum? thanks.


Solution

  • Try to use this code as a base to do what you want. Just ignore some words that are in Portuguese (my native language).

    #include <stdio.h>
    #include <conio.h>
    #include <stdlib.h>
    
    void seg_max(int *v, int n, int & x, int &y , int & max){
     int i,j;
     int soma; 
     max = -1; 
     for(i=0;i<n;i++){
      soma = 0;
      for(j=i;j<n;j++){
       soma += v[j];
       if( soma > max ){
        max = soma;
        x = i;
        y = j;
       }
      }
     }
    }
    
    int main(){
    int x,y,max;
    int v[] = {-2,1,-3,4,-1,2,1,-5,4};
    seg_max(v,9,x,y,max);
    printf("max sum [%d-%d] with the sum equal to %d\n", x,y,max);
    }