Maximization of Quadruple
You are given an array Arr, you have to find the maximum value of the expression (Arr[i1]-Arr[i2]+Arr[i3]-Arr[i4]) where i1>i2>i3>i4 and (0<=i1,i2,i3,i4<n).
Problem description:
The problem basically asks you to find the quadruple of numbers whose combination as (Arr[i1]-Arr[i2]+Arr[i3]-Arr[i4]) is maximum for particular indexes (i1,i2,i3,i4) such that (i1>i2>i3>i4).
You should also keep in mind the index range as i1 can maximum be (n-1) similarly (i2<=n-2),(i3<=n-3) and (i4<=(n-4)).
Input:
The first line of the input is the T number of test cases, each test case consists of N size of the input array, following line consist of N number of elements.
Output:
You need to print the value of maximum of the given expression in a separate line for each test case.
(a) Brute Force Approach:
In this approach, we will use the naive method of the nested loop. First, we will initialize ans variable with some minimum value then We will use for-loop each from 0 to its maximum index range.
As i1>i2>i3>i4 which implies i1<=n-1,i2<=n-2,i3<=n-3 and i4<=n-4 since we are using 0 based indexing.
Time complexity for the above approach in the worst case is: O(n^4)
Space complexity for the above approach in worst case i: O(1)
(b) Dynamic Programming Approach:
In this approach we will use extra space to beat time constraint as we are using exponential time in naive method.
Following steps will be used in our dynamic programming approach:
Time complexity for the above approach in the worst case is: O(n)
Space complexity for the above approach in the worst case is: O(1)
C++ Implementation (Brute Force Approach)
Output:
C++ Implementation (Dynamic Programming Approach)
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer