![]() |
VOOZH | about |
Given an array arr[] consisting of N integers, the task is to find the absolute difference between the minimum and maximum sum of any pairs of elements (arr[i], arr[j]) such that (i < j) and (arr[i] < arr[j]).
Examples:
Input: arr[] = {1, 2, 4, 7}
Output: 8
Explanation: All possible pairs are:
- (1, 2) ? Sum = 3
- (1, 4) ? Sum = 5
- (1, 7) ? Sum = 8
- (2, 4) ? Sum = 6
- (2, 7) ? Sum = 9
- (4, 7) ? Sum = 11
Therefore, the difference between maximum and minimum sum = 11 - 3 = 8.
Input: arr[] = {2, 5, 3}
Output: 2
Approach: The idea to solve the given problem is to create two auxiliary arrays to store minimum and maximum of suffixes of every index of suffixes of the given array and then find the required absolute difference.
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
7
Time Complexity: O(N)
Auxiliary Space: O(N)