Friday, February 28, 2014

Maximum Subarray Problem, Kadane's algo

The problem has been solved to death many a times(Just go do a simple google search for it) :)

Even then, here is a working C++ implementation of it:
/*
 Copyright: Puneet Sohi. 
 */

#include <iostream>
#include <tr1/unordered_map>
#include <vector>

using namespace std;
using namespace tr1;

void maxSubArr(int *a){
int currIdx = 0;
int maxStartIdx = 0;
int maxStartIdxTillNow = 0;
int maxEndIdx = 0;
int cumSum = 0;
int maxSum = 1; maxSum = maxSum << 31; //make maxSum most negative
int currItem = 0;
while(a[currIdx] != '\0'){
currItem = a[currIdx];
cumSum += currItem;
if(cumSum > maxSum){
maxSum = cumSum;
maxStartIdx = maxStartIdxTillNow;
maxEndIdx = currIdx;
}
else if (cumSum < 0){
cumSum = 0;
maxStartIdxTillNow = currIdx + 1;
}
currIdx++;
}
cout << "max indices: " << maxStartIdx  << " "<< maxEndIdx << endl;
cout << "max sum:  " << maxSum << endl;
return;
}



int main(){
    //Test Cases 
int a[] = {-1, 3, -5, 4, 6, -1, 2, -7, 13, -3};
//int b[] = {3, -1, -1, -1, -1, -1, 2, 0, 0, 0};
//int c[] = {-6,-2,-3,-4,-1,-5,-5};
int d[] = { 3, -1, -1, -1, -1, -1, 2, 0, 0, 0};
//int e[] = {};
//int f[] = {};

    maxSubArr(d);
return 0;

}

No comments:

Post a Comment