In one book (Introduction to Algorithm, but I don't remember which chapter) I learned that to solve Maximum difference between two elements problem:
Maximum difference between two elements such that larger element appears after the smaller number.
Examples: If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (Diff between 10 and 2). If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9)
is equal to solve the maximum subarray problem:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
In order to solve Maximum difference between two elements problem for
[2,3,10,6,4,8,1]
, it can be convert to a max subarray problem for array:
[1,7,-4,-2,4,-7]
where 1 is difference between 2,3; 7 is difference between 3,10; etc.
I am wondering why.