![]() |
VOOZH | about |
Given an array arr[], the task is to return the maximum value of increasing triplet (i, j, k) such that i < j < k and arr[i] < arr[j] < arr[k]. The value of a triplet (i, j, k) is arr[i] - arr[j] + arr[k].
Example:
Input: arr = {1, 2, 3,4, 5}
Output: 4Input: arr = {11, 2, 33, 4, 5}
Output: 0
Approach:
The idea is to use a greedy algorithm approach.
Here’s a step-by-step breakdown:
Edge Case Handling: If the array has less than 3 elements, it returns 0 because it’s impossible to form a triplet.
Right Maximum Array: It creates an array rightMax to store the maximum values from the right for each index. This array is filled from right to left.
set: A set is used to store the elements of the array. It keeps the elements in sorted order.
Main Logic: Iterates over the array from the second element to the second last element. For each element, it finds the element in the set that is just less than the current element. If such an element exists and the maximum value from the right for the current index is greater than the current element, it updates the maximum value with the difference between the element just less than the current element, the current element, and the maximum value from the right. The current element is then inserted into the set. Finally returns the maximum value found.
Steps-by-step approach:
Below is the implementation of the above approach:
4
Time Complexity: O(n log n)
Auxiliary Space: O(n)