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 106Input: 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.
Below is the implementation of the above approach:
// 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 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 |
// Java program for the above approach import 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 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 |
// C# program for the above approach using 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 triplets function 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:
#include <iostream> #include <set> using namespace std;
// Function that finds the maximum // valid triplets int max_valid_triplet( int A[], int n)
{ int ans = -1;
// Declare the left[] and
// right[] array
int left[n];
int right[n];
// Consider last element as maximum
int mx = 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 (mx > A[i])
right[i] = mx;
// Else store -1
else
right[i] = -1;
// Find the maximum for
// the next iteration
if (mx < A[i])
mx = A[i];
}
set< int > s;
for ( int i = 1; i < n; i++) {
// Insert previous element
// to the set
s.insert(A[i - 1]);
// Search for maximum element
// which is < present element
auto it = s.lower_bound(A[i]);
// If result is null there is
// no such element exists
// so store -1 at left[i]
if (it == s.begin())
left[i] = -1;
// Else store the result
else
left[i] = *(--it);
}
// 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 = max(ans, left[i] + A[i] * right[i]);
}
// Return the ans
return ans;
} // Driver Code int main()
{ // Given array arr[]
int A[] = { 7, 9, 3, 8, 11, 10 };
int n = sizeof (A) / sizeof (A[0]);
// Function Call
cout << max_valid_triplet(A, n) << endl;
return 0;
} |
// 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));
}
} |
# Python equivalent code # Function to find the maximum valid triplets def max_valid_triplet(A):
n = len (A)
ans = - 1
left = [ 0 ] * n
right = [ 0 ] * n
max_value = A[n - 1 ]
# Iterate the array from the last
for i in range (n - 2 , - 1 , - 1 ):
# If the present element is less than the maximum
# update the right[i] with previous maximum
if max_value > A[i]:
right[i] = max_value
# Else store -1
else :
right[i] = - 1
# Find the maximum for the next iteration
if max_value < A[i]:
max_value = A[i]
setn = set ()
for i in range ( 1 , n):
# Insert previous element to the set
setn.add(A[i - 1 ])
result = None
# Search for maximum element which is < present element
for j in range (A[i - 1 ], - 1 , - 1 ):
if j in setn:
result = j
break
# If result is None, there is no such element exists
# so store -1 at left[i]
if result is None :
left[i] = - 1
# Else store the result
else :
left[i] = result
# Traverse the original array
for i in range ( 1 , n - 1 ):
# Condition for valid triplet
if left[i] ! = - 1 and right[i] ! = - 1 :
# Find the value and update the maximum value
ans = max (ans, left[i] + A[i] * right[i])
# Return the ans
return ans
# Driver Code if __name__ = = '__main__' :
# Given array
A = [ 7 , 9 , 3 , 8 , 11 , 10 ]
# Function call
print (max_valid_triplet(A))
|
// 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 |
<script> // Javascript program for the above approach // Function that finds the maximum // valid triplets function 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 Code let 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)