Given an array A, maximize value of expression (A[s] - A[r] + A[q] - A[p]), where p, q, r, and s are indices of the array and s > r > q > p.

For example,

Input:  A[] = [3, 9, 10, 1, 30, 40]
 
Output: 46
 
Explanation: The expression (40 – 1 + 10 – 3) will result in the maximum value

Practice this problem

A naive solution would be to generate all combinations of such numbers. The time complexity of this solution would be O(n4), where n is the size of the input.

 
We can use dynamic programming to solve this problem. The idea is to create four lookup tables, first[], second[], third[], and fourth[], where:

  • first[] stores the maximum value of A[s].
  • second[] stores the maximum value of A[s] - A[r].
  • third[] stores the maximum value of A[s] - A[r] + A[q].
  • fourth[] stores the maximum value of A[s] - A[r] + A[q] - A[p].

The maximum value would then be present in index 0 of fourth[], which is our required answer. The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

46

Java


Download  Run Code

Output:

46

Python


Download  Run Code

Output:

46

The time complexity of the above solution is O(n) and requires O(n) extra space.