Maximum value of expression (arr[i] + arr[j] * arr[k]) formed from a valid Triplet
Last Updated :
15 Jul, 2025
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:
- 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++
// 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
// 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
# 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#
// 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
JavaScript
<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>
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:
C++
#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
// 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));
}
}
Python3
# 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#
// 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
JavaScript
<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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem