Actually it is the problem #10 of chapter 8 of Programming Pearls 2nd edition. It asked two questions: given an array A[] of integers(positive and nonpositive), how can you find a continuous subarray of A[] whose sum is closest to 0? Or closest to a certain value t?
I can think of a way to solve the problem closest to 0. Calculate the prefix sum array S[], where S[i] = A[0]+A[1]+...+A[i]. And then sort this S according to the element value, along with its original index information kept, to find subarray sum closest to 0, just iterate the S array and do the diff of the two neighboring values and update the minimum absolute diff.
Question is, what is the best way so solve second problem? Closest to a certain value t? Can anyone give a code or at least an algorithm? (If anyone has better solution to closest to zero problem, answers are welcome too)
Your solution for the 0 case seems ok to me. Here is my solution to the second case:
startto 0 (first index in the sorted prefix array)endtolast(last index of the prefix array)start0...lastand for each you find the correspondingend- the last index in which the prefix sum is such thatprefix[start]+prefix[end]>t. When you find thatendthe best solution forstartis eitherprefix[start]+prefix[end]orprefix[start]+prefix[end - 1](the latter taken only ifend> 0)endfor eachstartfrom scratch -prefix[start]increases in value when iterating over all possible values forstart, which means that in each iteration you are interested only in values <= the previous value ofend.start>endstartpositions.It can easily be proved that this will give you complexity of
O(n logn)for the entire algorithm.