Hi,
I was reading "programming pearls" book and stuck in some place. The (best) original solution for the problem (finding sub-array with max sum) is:
maxsofar = О
maxendinghere = О
for i = [0. n)
{
maxendinghere = max(maxendinghere + x[i], 0)
maxsofar = max(maxsofar, maxendinghere)
}
Then the problems is changed as follows and the program is asked to be modified:
Instead of finding sub-array with maximum sum, we have to find sub-array with sum closest to zero (not minimum) or some other number f.
- So I would solve this by just changing the function "max" to some function that will return the number which is closer to zero (or f).
- maxsofar would be initialized to an element closest to zero (or f)
This solution runs in O(n), but the author is giving a solution that's difficult and runs in O(nlogn) and claims that this the optimum solution (the best possible theoretically).
Please could you point out an error in my solution (if book says nlogn is best, then my solution must have some errors).
UPDATE: So my answer will be:
closest = get_element_closest_to_zero();
maxsofar = closest;
maxendinghere = 0;
for i = [0. n)
{
maxendinghere = closest_to_zero(maxendinghere + x[i], closest);
maxsofar = closest_to_zero(maxsofar, maxendinghere) ;
}
Thanks.