Thursday, August 28, 2008

Sub Array with Large Sum in Array

Prob: Given an array int[] x of n elements , how can we find the sub-sequence that yields the maximum sum. Note that negative numbers are also present in the array.

Sol: mini = -1, minv = 0, maxi1 = 0, maxi2 = 0, maxv = -999999999;

for i=0 to length of x
{
if (i>0)
x[i] += x[i-1];

if (x[i]-minv>=maxv) {
maxv = x[i]-minv;
maxi1 = mini+1;
maxi2 = i;
}
if (x[i] minv = x[i];
mini = i;
}
}

Values of indexes will be maxi1 and maxi2

No comments: