VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-maximum-value-of-increasing-triplet/

⇱ Find Maximum value of Increasing Triplet - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Maximum value of Increasing Triplet

Last Updated : 16 May, 2024

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: 4

Input: 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:

  • Initialize a array rightMax of the same size as arr.
  • Iterate through arr from the second-to-last element to the first, updating each element of rightMax with the maximum value encountered so far (including the current element).
  • Create st and Initialize maxVal:
    • Create a set named st to store elements of arr.
    • Insert the first element of arr into st.
    • Initialize maxVal to 0.
  • Iterate through arr (excluding first and last two elements):
    • For each element arr[i] from the second element to the second-to-last element:
      • Find the element in st that is just less than arr[i] using lower_bound.
      • If such an element exists:
        • Decrement the iterator to get the element just less than arr[i].
        • If rightMax[i + 1] (maximum value from the right) is greater than arr[i]:
          • Update maxVal with the maximum value found so far, calculated as the difference between the element just less than arr[i], arr[i], and rightMax[i + 1].
    • Insert arr[i] into st.
  • After iterating through all elements, return the calculated maxVal.

Below is the implementation of the above approach:


Output
4

Time Complexity: O(n log n)
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: