Maximum value of expression (arr[i] + arr[j] * arr[k]) formed from a valid Triplet

Given an array  arr[] of N integers. The task is to find the maximum value of (arr[i] + arr[j] * arr[k]) among every triplet (i, j, k) such that arr[i] < arr[j] < arr[k] and i < j < k. If there doesn’t exist any such triplets then print “-1″.

Examples:

Input: arr[]={7, 9, 3, 8, 11, 10}
Output: 106
Explanation:
The valid triplets are:
1) (7, 9, 11), and value of (arr[i] + arr[j] * arr[k]) is 106.
2) (7, 9, 10), and value of (arr[i] + arr[j] * arr[k]) is 97.
3) (7, 8, 10), and value of (arr[i] + arr[j] * arr[k]) is 87.
4) (7, 8, 11), and value of (arr[i] + arr[j] * arr[k]) is 105.
5) (3, 8, 10), and value of (arr[i] + arr[j] * arr[k]) is 83.
6) (3, 8, 11), and value of (arr[i] + arr[j] * arr[k]) is 91.
Therefore, the maximum among the values is 106

Input: arr[]={1, 2, 3}
Output: 7

 

Naive Approach: The idea is to generate all possible valid triplets (i, j, k) and print the maximum value of arr[i] + arr[j]*arr[k] among all the triplets. Below are the steps:

  1. Iterate over the array using three nested loops.
  2. For each valid triplets check if arr[i] < arr[j] < arr[k]. If so then the triplet is valid.
  3. Find the value of arr[i] + arr[j]*arr[k] for all such triplets if the above condition is true and store it in the variable called value.
  4. Keep updating the value of above expression to maximum value among all possible triplets.
  5. If no valid triplet found print -1 Otherwise print the maximum value.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that generate all valid
// triplets and calcluate the value
// of the valid triplets
void max_valid_triplet(int A[], int n)
{
    int ans = -1;
 
    // Generate all triplets
    for(int i = 0; i < n - 2; i++)
    {
        for(int j = i + 1; j < n - 1; j++)
        {
            for(int k = j + 1; k < n; k++)
            {
                 
                // Check whether the triplet
                // is valid or not
                if (A[i] < A[j] && A[j] < A[k])
                {
                    int value = A[i] + A[j] * A[k];
 
                    // Update the value
                    if (value > ans)
                    {
                        ans = value;
                    }
                }
            }
        }
    }
     
    // Print the maximum value
    cout << (ans);
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 7, 9, 3, 8, 11, 10 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    max_valid_triplet(arr, n);
    return 0;
}
 
// This code is contributed by chitranayal

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.Scanner;
 
class GFG {
 
    // Function that generate all valid
    // triplets and calcluate the value
    // of the valid triplets
    static void
    max_valid_triplet(int A[], int n)
    {
 
        int ans = -1;
 
        // Generate all triplets
        for (int i = 0; i < n - 2; i++) {
 
            for (int j = i + 1; j < n - 1; j++) {
 
                for (int k = j + 1; k < n; k++) {
 
                    // Check whether the triplet
                    // is valid or not
                    if (A[i] < A[j] && A[j] < A[k]) {
 
                        int value = A[i] + A[j] * A[k];
 
                        // Update the value
                        if (value > ans) {
                            ans = value;
                        }
                    }
                }
            }
        }
 
        // Print the maximum value
        System.out.println(ans);
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Given array arr[]
        int[] arr = new int[] { 7, 9, 3, 8, 11, 10 };
 
        int n = arr.length;
 
        // Function Call
        max_valid_triplet(arr, n);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function that generate all valid
# triplets and calcluate the value
# of the valid triplets
def max_valid_triplet(A, n):
 
    ans = -1;
 
    # Generate all triplets
    for i in range(0, n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
 
                # Check whether the triplet
                # is valid or not
                if (A[i] < A[j] and A[j] < A[k]):
                    value = A[i] + A[j] * A[k];
 
                    # Update the value
                    if (value > ans):
                        ans = value;
                     
    # Print the maximum value
    print(ans);
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr
    arr = [ 7, 9, 3, 8, 11, 10 ];
 
    n = len(arr);
 
    # Function call
    max_valid_triplet(arr, n);
 
# This code is contributed by Amit Katiyar 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
class GFG{
 
  // Function that generate all valid
  // triplets and calcluate the value
  // of the valid triplets
  static void max_valid_triplet(int[] A, int n)
  {
    int ans = -1;
 
    // Generate all triplets
    for (int i = 0; i < n - 2; i++)
    {
      for (int j = i + 1; j < n - 1; j++)
      {
        for (int k = j + 1; k < n; k++)
        {
 
          // Check whether the triplet
          // is valid or not
          if (A[i] < A[j] && A[j] < A[k])
          {
            int value = A[i] + A[j] * A[k];
 
            // Update the value
            if (value > ans)
            {
              ans = value;
            }
          }
        }
      }
    }
 
    // Print the maximum value
    Console.WriteLine(ans);
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    // Given array []arr
    int[] arr = new int[] { 7, 9, 3, 8, 11, 10 };
 
    int n = arr.Length;
 
    // Function Call
    max_valid_triplet(arr, n);
  }
}
 
// This code is contributed by gauravrajput1

chevron_right


Output: 



106



 

Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient approach: The above method can be optimized by using TreeSet in Java. Below are the steps:

  1. Create two arrays. One array (left) to store the maximum element on the left side which strictly less than the present element in the original array and another array (right) to store the right side maximum of the present element in the original array as shown in the below image for array arr[] = {7, 9, 3, 8, 11, 10}
     

  1. For the construction of the left array, we use TreeSet in Java, insert the elements into the TreeSet, use the lower() method in TreeSet which will return the greatest element in this set which is strictly less than the given element. If no such element exists in this TreeSet collection then this method returns a NULL.
  2. The elements in the left array will be arr[i] of the valid triplets and the elements in the right array will be arr[k] of the valid triplet.
  3. Now, traverse the original array from 1 to N – 1, to select arr[j] for the valid triplet.
  4. If left[i]!=-1 && right[i]!=-1 then there is a chance for forming triplet.
  5. Find the value arr[i] + arr[j]*arr[k] for all such valid triplets and update the ans according to the maximum value.
  6. Print the maximum value if it exists otherwise print “-1”.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function that finds the maximum
    // valid triplets
    static int max_valid_triplet(int A[], int n)
    {
        int ans = -1;
 
        // Declare the left[] and
        // right[] array
        int left[] = new int[n];
        int right[] = new int[n];
 
        // Consider last element as maximum
        int max = A[n - 1];
 
        // Iterate array from the last
        for (int i = n - 2; i >= 0; i--) {
 
            // If present is less the maximum
            // update the right[i] with
            // previous maximum
            if (max > A[i])
                right[i] = max;
 
            // Else store -1
            else
                right[i] = -1;
 
            // Find the maximum for
            // the next iteration
            if (max < A[i])
                max = A[i];
        }
 
        TreeSet<Integer> set = new TreeSet<Integer>();
        for (int i = 1; i < n; i++) {
 
            // Insert previous element
            // to the set
            set.add(A[i - 1]);
 
            Integer result = set.lower(A[i]);
 
            // Search for maximum element
            // which is < present element
 
            // If result is null there is
            // no such element exists
            // so store -1 at left[i]
            if (result == null)
                left[i] = -1;
 
            // Else store the result
            else
                left[i] = result;
        }
 
        // Traverse the original array
        for (int i = 1; i < n - 1; i++) {
 
            // Condition for valid triplet
            if (left[i] != -1
                && right[i] != -1)
 
                // Find the value and update
                // the maximum value
                ans = Math.max(ans,
                               left[i] + A[i] * right[i]);
        }
 
        // Return the ans
        return ans;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Given array arr[]
        int[] A = new int[] { 7, 9, 3, 8, 11, 10 };
        int n = A.length;
 
        // Function Call
        System.out.println(max_valid_triplet(A, n));
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function that finds the maximum
// valid triplets
static int max_valid_triplet(int []A, int n)
{
    int ans = -1;
 
    // Declare the []left and
    // []right array
    int []left = new int[n];
    int []right = new int[n];
 
    // Consider last element as maximum
    int max = A[n - 1];
 
    // Iterate array from the last
    for(int i = n - 2; i >= 0; i--)
    {
         
        // If present is less the maximum
        // update the right[i] with
        // previous maximum
        if (max > A[i])
            right[i] = max;
 
        // Else store -1
        else
            right[i] = -1;
 
        // Find the maximum for
        // the next iteration
        if (max < A[i])
            max = A[i];
    }
 
    SortedSet<int> set = new SortedSet<int>();
    for(int i = 1; i < n; i++)
    {
         
        // Insert previous element
        // to the set
        set.Add(A[i - 1]);
 
        int result = set.Min;
 
        // Search for maximum element
        // which is < present element
 
        // If result is null there is
        // no such element exists
        // so store -1 at left[i]
        if (result == 0)
            left[i] = -1;
 
        // Else store the result
        else
            left[i] = result;
    }
 
    // Traverse the original array
    for(int i = 1; i < n - 1; i++)
    {
         
        // Condition for valid triplet
        if (left[i] != -1 &&
           right[i] != -1)
 
            // Find the value and update
            // the maximum value
            ans = Math.Max(ans,
                           left[i] +
                              A[i] *
                          right[i]);
    }
 
    // Return the ans
    return ans;
}
 
// Driver Code
public static void Main(String []args)
{
     
    // Given array []arr
    int[] A = new int[]{ 7, 9, 3, 8, 11, 10 };
    int n = A.Length;
 
    // Function call
    Console.WriteLine(max_valid_triplet(A, n));
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Output: 

106



 

Time Complexity: O(N)
Auxiliary Space: O(N)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.