I recently encountered a question on a contest organised by CodeNation which is as follows.
You have been give an array comprising of numbers (ranging from -10^9 to +10^9) and the value of an array is defined as the sum of the absolute differences between each pair of consecutive entries in the array. You are allowed to reverse a contiguous subarray of the given array. What would be the maximum possible value of the array if you apply the given operation utmost once?
I am stuck on the O(n^2) approach to this problem. Can anyone please help me out?
There are two corner cases when the reversing subarray contains the first array element and when it contains last array element. We can consider those cases separately. Also if the array size is small (say n <= 3) the answer can be easily calculated.
Suppose we reverse the subarray [b...c] in the initial array m = [... a b ... c d ...]. So the difference in the array value will be
This value can be positive only when both a, b are greater than any of c, d or both c, d are greater then a, b. If we have first case then the difference can be expressed as
We can support two additional arrays for the adjacent numbers: minp[n] and rmaxp[n]. minp[i] represents the minimum value of the pair values m[i] and m[i+1], keeping the maximum value among all values from the beggining of the initial array:
rmaxp[i] means the maximum value of m[i] and m[i+1], keeping the minimum value among all values from the end of the initial array:
Now all we should do is to find maximum positive value of minp[i-1]-rmaxp[i+1] for each valid index i (because the index of number b should be strictly smaller than the index of number c). The second case can be proceeded analogously.
PS Couldn't you give the link to the problem?
https://www.hackerrank.com/tests/c7c0j43gssa fill the details and login to it
Is there any mathematical manipulation to prove first expression?
Sorry, what do you mean?
How can we show that both a & b are greater than c & d.