![]() |
VOOZH | about |
Given an array of distinct positive integers, the task is to find the maximum product of increasing subsequence of size 3, i.e., we need to find arr[i]*arr[j]*arr[k] such that arr[i] < arr[j] < arr[k] and i < j < k < n
Examples:
Input: arr[] = {10, 11, 9, 5, 6, 1, 20}
Output: 2200
Explanation: Increasing sub-sequences of size three are {10, 11, 20} => product 10*11*20 = 2200 {5, 6, 20} => product 5*6*20 = 600 Maximum product : 2200Input: arr[] = {1, 2, 3, 4}
Output: 24
A Simple solution is to use three nested loops to consider all subsequences of size 3 such that arr[i] < arr[j] < arr[k] & i < j < k). For each such sub-sequence calculate product and update maximum product if required.
2200
Time Complexity: Since it's running 3 for loops it's Time Complexity is O(n^3).
Auxiliary Space: O(1)
An Efficient solution takes O(n log n) time. The idea is to find the following two for every element. Using below two, we find the largest product of an increasing subsequence with an element as middle element. To find the largest product, we simply multiply the element below two.
Note : We need largest of as we want to maximize the product.
To find largest element on right side, we use the approach discussed here. We just need to traverse array from right and keep track of maximum element seen so far.
To find closest smaller element, we use self-balancing binary search tree as we can find closest smaller in O(Log n) time. In C++, set implements the same and we can use it to find closest element.
Below is the implementation of above idea. In the implementation, we first find smaller for all elements. Then we find greater element and result in single loop.
2200
Time Complexity: O(n log n) [ Inset and find operation in set take logn time ]
Auxiliary Space: O(n)