I have been given a sequence of numbers a_1,a_2,...,a_n. This amount is equal S=a_1+a_2+...+a_n, and I need to find a subsequence a_i,...,a_jsuch that it min(S-(a_i+...+a_j),a_i+...+a_j)is the maximum possible (both amounts must be nonempty).
Example:
1,2,3,4,5sequence 3,4, because then min(S-(a_i+...+a_j),a_i+...+a_j)=min(8,7)=7(and this is the maximum possible that can be checked for other subsequences).
I tried to do this with difficulty.
I load all the values into an array tab[n].
I do it n-1once tab[i]+=tab[i-j]. So that tab[j]represents the amount from the beginning to j.
I check all possible amounts a_i+...+a_j=tab[j]-tab[i-1]and subtract it from the amount, take a minimum and see if it is more than before.
Required O(n^2). It makes me very sad and unhappy. Is there a better way?
source
share