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

18 Aug, 2021
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: 106Explanation: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:
Iterate over the array using three nested loops.For each valid triplets check if arr[i] < arr[j] < arr[k]. If so then the triplet is valid.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.Keep updating the value of above expression to maximum value among all possible triplets.If no valid triplet found print -1 Otherwise print the maximum value.
Iterate over the array using three nested loops.
For each valid triplets check if arr[i] < arr[j] < arr[k]. If so then the triplet is valid.
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.
Keep updating the value of above expression to maximum value among all possible triplets.
If no valid triplet found print -1 Otherwise print the maximum value.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that generate all valid// triplets and calculate the value// of the valid tripletsvoid 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 Codeint 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
// Java program for the above approachimport java.util.Scanner; class GFG {     // Function that generate all valid    // triplets and calculate 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);    }}
# Python3 program for the above approach # Function that generate all valid# triplets and calculate the value# of the valid tripletsdef 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 Codeif __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 
// C# program for the above approachusing System;class GFG{   // Function that generate all valid  // triplets and calculate 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
<script>// JavaScript program for the above approach // Function that generate all valid// triplets and calculate the value// of the valid tripletsfunction max_valid_triplet(A, n){    let ans = -1;     // Generate all triplets    for(let i = 0; i < n - 2; i++)    {        for(let j = i + 1; j < n - 1; j++)        {            for(let k = j + 1; k < n; k++)            {                                 // Check whether the triplet                // is valid or not                if (A[i] < A[j] && A[j] < A[k])                {                    let value = A[i] + A[j] * A[k];                     // Update the value                    if (value > ans)                    {                        ans = value;                    }                }            }        }    }         // Print the maximum value    document.write(ans);} // Driver Code     // Given array arr[]    let arr = [ 7, 9, 3, 8, 11, 10 ];    let n = arr.length;     // Function call    max_valid_triplet(arr, n); // This code is contributed by Surbhi Tyagi.</script>
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:
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}:  
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.
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.
Now, traverse the original array from 1 to N – 1, to select arr[j] for the valid triplet.
If left[i]!=-1 && right[i]!=-1 then there is a chance for forming triplet.
Find the value arr[i] + arr[j]*arr[k] for all such valid triplets and update the ans according to the maximum value.
Print the maximum value if it exists otherwise print “-1”.
Below is the implementation of the above approach:
Java
C#
Javascript
// Java program for the above approachimport 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));    }}
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that finds the maximum// valid tripletsstatic 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 Codepublic 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
<script> // Javascript program for the above approach // Function that finds the maximum// valid tripletsfunction max_valid_triplet(A, n){    let ans = -1;      // Declare the []left and    // []right array    let left = new Array(n);       let right = new Array(n);             for(let i = 0; i < n; i++)    {        left[i] = 0;        right[i] = 0;    }         // Consider last element as maximum    let max = A[n - 1];      // Iterate array from the last    for(let 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];    }      let set = new Set();    for(let i = 1; i < n; i++)    {                  // Insert previous element        // to the set        set.add(A[i - 1]);          let result = Math.min(...Array.from(set));          // 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(let 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 Codelet A = [ 7, 9, 3, 8, 11, 10 ];let n = A.length; document.write(max_valid_triplet(A, n)); // This code is contributed by avanitrachhadiya2155 </script>
106
 
Time Complexity: O(N)Auxiliary Space: O(N) 
ukasp
GauravRajput1
amit143katiyar
surbhityagi15
avanitrachhadiya2155
singghakshay
java-treeset
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7