Given one integer array, you have to find out two disjoint continuous sub-array A and B, which maximate the absolute value of SUM(A)-SUM(B).
For example, [2,-1,-2,1,-4,2,8], A=[-1,-2,1,-4], B=[2,8], the maximum is 16.
Resolve
It’s obvious see that to one array with N length, there is N-1 positions to seperate the original array. Then we get left sub-array and right sub-array.
We have to iterate the left and right part and find out the minimum and maximum respectively using dynamic programming method. It’s important to figure out that, in front of one number position x, the minimum VAL will be VAL[x] = MIN { VAL[x-1]+arr[x], arr[x] } (similar to maximum). Then we could get several minimal (or maximal) sumary value (different end positions) if we notice to mark in all the minimal (or maximal) sumary in all positions.
This algorithm will get O(N) time complexity.
Code
Notice: this article use BY-NC-SA license. Please specify the source: Awarrior