Maximum product of a triplet (subsequence of size 3) in array
Given an integer array, find a maximum product of a triplet in the array.
Examples:
Input: [10, 3, 5, 6, 20]
Output: 1200
Explanation: Multiplication of 10, 6 and 20
Input: [-10, -3, -5, -6, -20]
Output: -90
Input: [1, -4, 3, -6, 7, 0]
Output: 168
Naive Approach:
A simple solution is to check for every triplet using three nested loops. Below is its implementation :
C++
#include <bits/stdc++.h>
using namespace std;
int maxProduct( int arr[], int n)
{
if (n < 3)
return -1;
int max_product = INT_MIN;
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++)
max_product = max(max_product,
arr[i] * arr[j] * arr[k]);
return max_product;
}
int main()
{
int arr[] = { 10, 3, 5, 6, 20 };
int n = sizeof (arr) / sizeof (arr[0]);
int max = maxProduct(arr, n);
if (max == -1)
cout << "No Triplet Exists" ;
else
cout << "Maximum product is " << max;
return 0;
}
|
Java
class GFG {
static int maxProduct( int []arr, int n)
{
if (n < 3 )
return - 1 ;
int max_product = Integer.MIN_VALUE;
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++)
max_product = Math.max(max_product,
arr[i] * arr[j] * arr[k]);
return max_product;
}
public static void main (String [] args)
{
int []arr = { 10 , 3 , 5 , 6 , 20 };
int n = arr.length;;
int max = maxProduct(arr, n);
if (max == - 1 )
System.out.println( "No Triplet Exists" );
else
System.out.println( "Maximum product is " + max);
}
}
|
Python3
import sys
def maxProduct(arr, n):
if n < 3 :
return - 1
max_product = - (sys.maxsize - 1 )
for i in range ( 0 , n - 2 ):
for j in range (i + 1 , n - 1 ):
for k in range (j + 1 , n):
max_product = max (
max_product, arr[i]
* arr[j] * arr[k])
return max_product
arr = [ 10 , 3 , 5 , 6 , 20 ]
n = len (arr)
max = maxProduct(arr, n)
if max = = - 1 :
print ( "No Triplet Exits" )
else :
print ( "Maximum product is" , max )
|
C#
using System;
class GFG {
static int maxProduct( int []arr, int n)
{
if (n < 3)
return -1;
int max_product = int .MinValue;
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++)
max_product = Math.Max(max_product,
arr[i] * arr[j] * arr[k]);
return max_product;
}
public static void Main ()
{
int []arr = { 10, 3, 5, 6, 20 };
int n = arr.Length;;
int max = maxProduct(arr, n);
if (max == -1)
Console.WriteLine( "No Triplet Exists" );
else
Console.WriteLine( "Maximum product is " + max);
}
}
|
Javascript
<script>
function maxProduct(arr, n)
{
if (n < 3)
return -1;
let max_product = Number.MIN_VALUE;
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++)
max_product = Math.max(max_product,
arr[i] * arr[j] * arr[k]);
return max_product;
}
let arr = [ 10, 3, 5, 6, 20 ];
let n = arr.length;;
let max = maxProduct(arr, n);
if (max == -1)
document.write( "No Triplet Exists" );
else
document.write( "Maximum product is " + max);
</script>
|
PHP
<?php
function maxProduct( $arr , $n )
{
$INT_MIN = 0;
if ( $n < 3)
return -1;
$max_product = $INT_MIN ;
for ( $i = 0; $i < $n - 2; $i ++)
for ( $j = $i + 1; $j < $n - 1; $j ++)
for ( $k = $j + 1; $k < $n ; $k ++)
$max_product = max( $max_product ,
$arr [ $i ] * $arr [ $j ] * $arr [ $k ]);
return $max_product ;
}
$arr = array (10, 3, 5, 6, 20 );
$n = sizeof( $arr );
$max = maxProduct( $arr , $n );
if ( $max == -1)
echo "No Triplet Exists" ;
else
echo "Maximum product is " , $max ;
?>
|
Output
Maximum product is 1200
Time Complexity: O(n3)
Auxiliary Space: O(1)
Approach 2:
- Construct four auxiliary arrays leftMax[], rightMax[], leftMin[] and rightMin[] of same size as input array.
- Fill leftMax[], rightMax[], leftMin[] and rightMin[] in below manner.
- leftMax[i] will contain maximum element on left of arr[i] excluding arr[i]. For index 0, left will contain -1.
- leftMin[i] will contain minimum element on left of arr[i] excluding arr[i]. For index 0, left will contain -1.
- rightMax[i] will contain maximum element on right of arr[i] excluding arr[i]. For index n-1, right will contain -1.
- rightMin[i] will contain minimum element on right of arr[i] excluding arr[i]. For index n-1, right will contain -1.
- For all array indexes i except first and last index, compute maximum of arr[i]*x*y where x can be leftMax[i] or leftMin[i] and y can be rightMax[i] or rightMin[i].
- Return the maximum from step 3.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxProduct( int arr[], int n)
{
if (n < 3)
return -1;
vector< int > leftMin(n, -1);
vector< int > rightMin(n, -1);
vector< int > leftMax(n, -1);
vector< int > rightMax(n, -1);
int max_product = INT_MIN;
int max_sum = arr[0];
int min_sum = arr[0];
for ( int i = 1; i < n; i++)
{
leftMax[i] = max_sum;
if (arr[i] > max_sum)
max_sum = arr[i];
leftMin[i] = min_sum;
if (arr[i] < min_sum)
min_sum = arr[i];
}
max_sum = arr[n - 1];
min_sum = arr[n - 1];
for ( int j = n - 2; j >= 0; j--)
{
rightMax[j] = max_sum;
if (arr[j] > max_sum)
max_sum = arr[j];
rightMin[j] = min_sum;
if (arr[j] < min_sum)
min_sum = arr[j];
}
for ( int i = 1; i < n - 1; i++)
{
int max1 = max(arr[i] * leftMax[i] * rightMax[i],
arr[i] * leftMin[i] * rightMin[i]);
int max2 = max(arr[i] * leftMax[i] * rightMin[i],
arr[i] * leftMin[i] * rightMax[i]);
max_product = max(max_product, max(max1, max2));
}
return max_product;
}
int main()
{
int arr[] = { 1, 4, 3, -6, -7, 0 };
int n = sizeof (arr) / sizeof (arr[0]);
int max = maxProduct(arr, n);
if (max == -1)
cout << "No Triplet Exists" ;
else
cout << "Maximum product is " << max;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int maxProduct( int []arr, int n)
{
if (n < 3 )
return - 1 ;
int [] leftMin = new int [n];
int [] rightMin = new int [n];
int [] leftMax = new int [n];
int [] rightMax = new int [n];
Arrays.fill(leftMin, - 1 );
Arrays.fill(leftMax, - 1 );
Arrays.fill(rightMax, - 1 );
Arrays.fill(rightMin, - 1 );
int max_product = Integer.MIN_VALUE;
int max_sum = arr[ 0 ];
int min_sum = arr[ 0 ];
for ( int i = 1 ; i < n; i++)
{
leftMax[i] = max_sum;
if (arr[i] > max_sum)
max_sum = arr[i];
leftMin[i] = min_sum;
if (arr[i] < min_sum)
min_sum = arr[i];
}
max_sum = arr[n - 1 ];
min_sum = arr[n - 1 ];
for ( int j = n - 2 ; j >= 0 ; j--)
{
rightMax[j] = max_sum;
if (arr[j] > max_sum)
max_sum = arr[j];
rightMin[j] = min_sum;
if (arr[j] < min_sum)
min_sum = arr[j];
}
for ( int i = 1 ; i < n - 1 ; i++)
{
int max1 = Math.max(arr[i] * leftMax[i] * rightMax[i],
arr[i] * leftMin[i] * rightMin[i]);
int max2 = Math.max(arr[i] * leftMax[i] * rightMin[i],
arr[i] * leftMin[i] * rightMax[i]);
max_product = Math.max(max_product, Math.max(max1, max2));
}
return max_product;
}
public static void main (String[] args)
{
int []arr = { 1 , 4 , 3 , - 6 , - 7 , 0 };
int n = arr.length;
int max = maxProduct(arr, n);
if (max == - 1 )
System.out.println( "No Triplet Exists" );
else
System.out.println( "Maximum product is " +max);
}
}
|
Python3
import sys
def maxProduct(arr, n):
if (n < 3 ):
return - 1
leftMin = [ - 1 for i in range (n)]
rightMin = [ - 1 for i in range (n)]
leftMax = [ - 1 for i in range (n)]
rightMax = [ - 1 for i in range (n)]
max_product = - sys.maxsize - 1
max_sum = arr[ 0 ]
min_sum = arr[ 0 ]
for i in range ( 1 , n):
leftMax[i] = max_sum
if (arr[i] > max_sum):
max_sum = arr[i]
leftMin[i] = min_sum
if (arr[i] < min_sum):
min_sum = arr[i]
max_sum = arr[n - 1 ]
min_sum = arr[n - 1 ]
for j in range (n - 2 , - 1 , - 1 ):
rightMax[j] = max_sum
if (arr[j] > max_sum):
max_sum = arr[j]
rightMin[j] = min_sum
if (arr[j] < min_sum):
min_sum = arr[j]
for i in range ( 1 , n - 1 ):
max1 = max (arr[i] * leftMax[i] * rightMax[i],
arr[i] * leftMin[i] * rightMin[i])
max2 = max (arr[i] * leftMax[i] * rightMin[i],
arr[i] * leftMin[i] * rightMax[i])
max_product = max (max_product, max (max1, max2))
return max_product
arr = [ 1 , 4 , 3 , - 6 , - 7 , 0 ]
n = len (arr)
Max = maxProduct(arr, n)
if ( Max = = - 1 ):
print ( "No Triplet Exists" )
else :
print ( "Maximum product is" , Max )
|
C#
using System;
class GFG
{
static int maxProduct( int []arr, int n)
{
if (n < 3)
return -1;
int [] leftMin= new int [n];
int [] rightMin= new int [n];
int [] leftMax= new int [n];
int [] rightMax= new int [n];
Array.Fill(leftMin,-1);
Array.Fill(leftMax,-1);
Array.Fill(rightMax,-1);
Array.Fill(rightMin,-1);
int max_product = int .MinValue;
int max_sum = arr[0];
int min_sum = arr[0];
for ( int i = 1; i < n; i++)
{
leftMax[i] = max_sum;
if (arr[i] > max_sum)
max_sum = arr[i];
leftMin[i] = min_sum;
if (arr[i] < min_sum)
min_sum = arr[i];
}
max_sum = arr[n - 1];
min_sum = arr[n - 1];
for ( int j = n - 2; j >= 0; j--)
{
rightMax[j] = max_sum;
if (arr[j] > max_sum)
max_sum = arr[j];
rightMin[j] = min_sum;
if (arr[j] < min_sum)
min_sum = arr[j];
}
for ( int i = 1; i < n - 1; i++)
{
int max1 = Math.Max(arr[i] * leftMax[i] * rightMax[i],
arr[i] * leftMin[i] * rightMin[i]);
int max2 = Math.Max(arr[i] * leftMax[i] * rightMin[i],
arr[i] * leftMin[i] * rightMax[i]);
max_product = Math.Max(max_product, Math.Max(max1, max2));
}
return max_product;
}
static void Main()
{
int []arr = { 1, 4, 3, -6, -7, 0 };
int n = arr.Length;
int max = maxProduct(arr, n);
if (max == -1)
Console.WriteLine( "No Triplet Exists" );
else
Console.WriteLine( "Maximum product is " +max);
}
}
|
Javascript
<script>
function maxProduct(arr , n)
{
if (n < 3)
return -1;
leftMin = Array.from({length: n}, (_, i) => -1);
rightMin = Array.from({length: n}, (_, i) => -1);
leftMax = Array.from({length: n}, (_, i) => -1);
rightMax = Array.from({length: n}, (_, i) => -1);
var max_product = Number.MIN_VALUE;
var max_sum = arr[0];
var min_sum = arr[0];
for (i = 1; i < n; i++)
{
leftMax[i] = max_sum;
if (arr[i] > max_sum)
max_sum = arr[i];
leftMin[i] = min_sum;
if (arr[i] < min_sum)
min_sum = arr[i];
}
max_sum = arr[n - 1];
min_sum = arr[n - 1];
for (j = n - 2; j >= 0; j--)
{
rightMax[j] = max_sum;
if (arr[j] > max_sum)
max_sum = arr[j];
rightMin[j] = min_sum;
if (arr[j] < min_sum)
min_sum = arr[j];
}
for (i = 1; i < n - 1; i++)
{
var max1 = Math.max(arr[i] * leftMax[i] * rightMax[i],
arr[i] * leftMin[i] * rightMin[i]);
var max2 = Math.max(arr[i] * leftMax[i] * rightMin[i],
arr[i] * leftMin[i] * rightMax[i]);
max_product = Math.max(max_product, Math.max(max1, max2));
}
return max_product;
}
var arr = [ 1, 4, 3, -6, -7, 0 ];
var n = arr.length;
var max = maxProduct(arr, n);
if (max == -1)
document.write( "No Triplet Exists" );
else
document.write( "Maximum product is " +max);
</script>
|
PHP
<?php
function maxProduct( $arr , $n )
{
if ( $n < 3)
return -1;
$leftMin = array_fill (0, $n , -1);
$rightMin = array_fill (0, $n , -1);
$leftMax = array_fill (0, $n , -1);
$rightMax = array_fill (0, $n , -1);
$max_product = PHP_INT_MIN;
$max_sum = $arr [0];
$min_sum = $arr [0];
for ( $i = 1; $i < $n ; $i ++)
{
$leftMax [ $i ] = $max_sum ;
if ( $arr [ $i ] > $max_sum )
$max_sum = $arr [ $i ];
$leftMin [ $i ] = $min_sum ;
if ( $arr [ $i ] < $min_sum )
$min_sum = $arr [ $i ];
}
$max_sum = $arr [ $n - 1];
$min_sum = $arr [ $n - 1];
for ( $j = $n - 2; $j >= 0; $j --)
{
$rightMax [ $j ] = $max_sum ;
if ( $arr [ $j ] > $max_sum )
$max_sum = $arr [ $j ];
$rightMin [ $j ] = $min_sum ;
if ( $arr [ $j ] < $min_sum )
$min_sum = $arr [ $j ];
}
for ( $i = 1; $i < $n - 1; $i ++)
{
$max1 = max( $arr [ $i ] * $leftMax [ $i ] * $rightMax [ $i ],
$arr [ $i ] * $leftMin [ $i ] * $rightMin [ $i ]);
$max2 = max( $arr [ $i ] * $leftMax [ $i ] * $rightMin [ $i ],
$arr [ $i ] * $leftMin [ $i ] * $rightMax [ $i ]);
$max_product = max( $max_product , max( $max1 , $max2 ));
}
return $max_product ;
}
$arr = array ( 1, 4, 3, -6, -7, 0 );
$n = count ( $arr );
$max = maxProduct( $arr , $n );
if ( $max == -1)
echo "No Triplet Exists" ;
else
echo "Maximum product is " . $max ;
?>
|
Output
Maximum product is 168
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 3: Using priority queues.
- Create two Priority Queues. The first one (pqmin) is of default order and the Second one (pqmax) is of reverse order.
- Iterate through the array and insert all elements in both priority queues.
- Initialize a variable maximum with the first element in pqmax and remove it from pqmax.
- Create two variables product1 and product2.
- product1= maximum*pqmax.poll()*pqmax.poll().
- product2= maximum*pqmin.poll()*pqmin.poll().
- return the greatest of product1 and product2.
Below is the implementation of the above approach :
C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int maxProduct( int arr[], int n)
{
if (n < 3) {
return -1;
}
priority_queue< int , vector< int >, greater< int > > pqmin;
priority_queue< int > pqmax;
for ( int i = 0; i < n; i++) {
pqmin.push(arr[i]);
pqmax.push(arr[i]);
}
int maximum = pqmax.top();
pqmax.pop();
int product1 = maximum * pqmax.top() * pqmax.top();
pqmax.push(maximum);
int min1 = pqmin.top();
pqmin.pop();
int min2 = pqmin.top();
pqmin.pop();
int product2 = maximum * min1 * min2;
return max(product1, product2);
}
int main()
{
int arr[] = { -10, -3, 5, 6, -20 };
int n = sizeof (arr) / sizeof (arr[0]);
int max = maxProduct(arr, n);
if (max == -1) {
cout << "No Triplet Exists" ;
}
else {
cout << "Maximum triplet product is = " << max;
}
return 0;
}
|
Java
import java.util.*;
class GFG {
static int maxProduct( int arr[], int n)
{
if (n < 3 ) {
return - 1 ;
}
PriorityQueue<Integer> pqmin
= new PriorityQueue<>();
PriorityQueue<Integer> pqmax = new PriorityQueue<>(
Comparator.reverseOrder());
for ( int i = 0 ; i < arr.length; i++) {
pqmin.add(arr[i]);
pqmax.add(arr[i]);
}
int maximum = pqmax.poll();
int product1
= maximum * pqmax.poll() * pqmax.poll();
int product2
= maximum * pqmin.poll() * pqmin.poll();
return product1 > product2 ? product1 : product2;
}
public static void main(String[] args)
{
int arr[] = { - 10 , - 3 , 5 , 6 , - 20 };
int n = arr.length;
int max = maxProduct(arr, n);
if (max == - 1 ) {
System.out.println( "No Triplet Exists" );
}
else {
System.out.println(
"Maximum triplet product is = " + max);
}
}
}
|
Python3
import heapq
def maxProduct(arr):
if len (arr) < 3 :
return - 1
pqmin = []
pqmax = []
for i in range ( len (arr)):
heapq.heappush(pqmin, arr[i])
heapq.heappush(pqmax, - arr[i])
maximum = - heapq.heappop(pqmax)
product1 = maximum * ( - pqmax[ 0 ]) * ( - pqmax[ 1 ])
heapq.heappush(pqmax, - maximum)
min1 = heapq.heappop(pqmin)
min2 = heapq.heappop(pqmin)
product2 = maximum * min1 * min2
return max (product1, product2)
arr = [ - 10 , - 3 , 5 , 6 , - 20 ]
max = maxProduct(arr)
if max = = - 1 :
print ( "No Triplet Exists" )
else :
print ( "Maximum triplet product is =" , max )
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
static int MaxProduct( int [] arr, int n)
{
if (n < 3) {
return -1;
}
var pqmin = new SortedSet< int >();
var pqmax = new SortedSet< int >(Comparer< int >.Create(
(x, y) => y.CompareTo(x)));
foreach ( var item in arr) {
pqmin.Add(item);
pqmax.Add(item);
}
var maximum = pqmax.First();
pqmax.Remove(maximum);
var product1
= maximum * pqmax.First() * pqmax.First();
pqmax.Add(maximum);
var min1 = pqmin.Min;
pqmin.Remove(min1);
var min2 = pqmin.Min;
pqmin.Remove(min2);
var product2 = maximum * min1 * min2;
return Math.Max(product1, product2);
}
static void Main() {
var arr = new int [] { -10, -3, 5, 6, -20 };
var n = arr.Length;
var max = MaxProduct(arr, n);
if (max == -1) {
Console.WriteLine( "No Triplet Exists" );
}
else {
Console.WriteLine(
$ "Maximum triplet product is = {max}" );
}
}
}
|
Javascript
class PriorityQueueMin {
constructor() {
this .queue = [];
}
push(value) {
this .queue.push(value);
this .queue.sort((a, b) => a - b);
}
pop() {
return this .queue.shift();
}
peek() {
return this .queue[0];
}
isEmpty() {
return this .queue.length === 0;
}
}
class PriorityQueueMax {
constructor() {
this .queue = [];
}
push(value) {
this .queue.push(value);
this .queue.sort((a, b) => b - a);
}
pop() {
return this .queue.shift();
}
peek() {
return this .queue[0];
}
isEmpty() {
return this .queue.length === 0;
}
}
function maxProduct(arr, n) {
if (n < 3) {
return -1;
}
const pqMin = new PriorityQueueMin();
const pqMax = new PriorityQueueMax();
for (let i = 0; i < n; i++) {
pqMin.push(arr[i]);
pqMax.push(arr[i]);
}
const max = pqMax.peek();
pqMax.pop();
const product1 = max * pqMax.peek() * pqMax.peek();
pqMax.push(max);
const min1 = pqMin.peek();
pqMin.pop();
const min2 = pqMin.peek();
const product2 = max * min1 * min2;
return Math.max(product1, product2);
}
const arr = [-10, -3, 5, 6, -20];
const n = arr.length;
const max = maxProduct(arr, n);
console.log( "Maximum triplet product is = " + max);
|
Output
Maximum triplet product is = 1200
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 4:
- Sort the array using some efficient in-place sorting algorithm in ascending order.
- Return the maximum product of the last three elements of the array and the product of the first two elements and last element.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
int maxProduct( int arr[], int n)
{
if (n < 3)
return -1;
sort(arr, arr + n);
return max(arr[0] * arr[1] * arr[n - 1],
arr[n - 1] * arr[n - 2] * arr[n - 3]);
}
int main()
{
int arr[] = { -10, -3, 5, 6, -20 };
int n = sizeof (arr) / sizeof (arr[0]);
int max = maxProduct(arr, n);
if (max == -1)
cout << "No Triplet Exists" ;
else
cout << "Maximum product is " << max;
return 0;
}
|
Java
import java.util.Arrays;
class GFG {
static int maxProduct( int arr[], int n) {
if (n < 3 ) {
return - 1 ;
}
Arrays.sort(arr);
return Math.max(arr[ 0 ] * arr[ 1 ] * arr[n - 1 ],
arr[n - 1 ] * arr[n - 2 ] * arr[n - 3 ]);
}
public static void main(String[] args) {
int arr[] = {- 10 , - 3 , 5 , 6 , - 20 };
int n = arr.length;
int max = maxProduct(arr, n);
if (max == - 1 ) {
System.out.println( "No Triplet Exists" );
} else {
System.out.println( "Maximum product is " + max);
}
}
}
|
Python3
def maxProduct(arr, n):
if n < 3 :
return - 1
arr.sort()
return max (arr[ 0 ] * arr[ 1 ] * arr[n - 1 ],
arr[n - 1 ] * arr[n - 2 ] * arr[n - 3 ])
if __name__ = = "__main__" :
arr = [ - 10 , - 3 , 5 , 6 , - 20 ]
n = len (arr)
_max = maxProduct(arr, n)
if _max = = - 1 :
print ( "No Triplet Exists" )
else :
print ( "Maximum product is" , _max)
|
C#
using System;
public class GFG {
static int maxProduct( int []arr, int n) {
if (n < 3) {
return -1;
}
Array.Sort(arr);
return Math.Max(arr[0] * arr[1] * arr[n - 1],
arr[n - 1] * arr[n - 2] * arr[n - 3]);
}
public static void Main() {
int []arr = {-10, -3, 5, 6, -20};
int n = arr.Length;
int max = maxProduct(arr, n);
if (max == -1) {
Console.WriteLine( "No Triplet Exists" );
} else {
Console.WriteLine( "Maximum product is " + max);
}
}
}
|
Javascript
<script>
function maxProduct(arr, n)
{
if (n < 3)
{
return -1;
}
arr.sort();
return Math.max(arr[0] * arr[1] * arr[n - 1],
arr[n - 1] * arr[n - 2] * arr[n - 3]);
}
var arr = [-10, -3, 5, 6, -20];
var n = arr.length;
var max = maxProduct(arr, n);
if (max == -1)
{
document.write( "No Triplet Exists" );
}
else
{
document.write( "Maximum product is " + max);
}
</script>
|
PHP
<?php
function maxProduct( $arr , $n )
{
if ( $n < 3)
{
return -1;
}
sort( $arr );
return max( $arr [0] * $arr [1] * $arr [ $n - 1],
$arr [ $n - 1] * $arr [ $n - 2] * $arr [ $n - 3]);
}
$arr = array (-10, -3, 5, 6, -20);
$n = sizeof( $arr );
$max = maxProduct( $arr , $n );
if ( $max == -1)
{
echo ( "No Triplet Exists" );
}
else
{
echo ( "Maximum product is " . $max );
}
|
Output
Maximum product is 1200
Time Complexity: O(n log(n))
Auxiliary Space: O(1)
Approach 5:
- Scan the array and compute the Maximum, second maximum and third maximum element present in the array.
- Scan the array and compute Minimum and second minimum element present in the array.
- Return the maximum of product of Maximum, second maximum and third maximum and product of Minimum, second minimum and Maximum element.
Note: Step 1 and Step 2 can be done in a single traversal of the array.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
int maxProduct( int arr[], int n)
{
if (n < 3)
return -1;
int maxA = INT_MIN, maxB = INT_MIN, maxC = INT_MIN;
int minA = INT_MAX, minB = INT_MAX;
for ( int i = 0; i < n; i++)
{
if (arr[i] > maxA)
{
maxC = maxB;
maxB = maxA;
maxA = arr[i];
}
else if (arr[i] > maxB)
{
maxC = maxB;
maxB = arr[i];
}
else if (arr[i] > maxC)
maxC = arr[i];
if (arr[i] < minA)
{
minB = minA;
minA = arr[i];
}
else if (arr[i] < minB)
minB = arr[i];
}
return max(minA * minB * maxA,
maxA * maxB * maxC);
}
int main()
{
int arr[] = { 1, -4, 3, -6, 7, 0 };
int n = sizeof (arr) / sizeof (arr[0]);
int max = maxProduct(arr, n);
if (max == -1)
cout << "No Triplet Exists" ;
else
cout << "Maximum product is " << max;
return 0;
}
|
Java
import java.util.*;
class GFG{
static int maxProduct( int []arr, int n)
{
if (n < 3 )
return - 1 ;
int maxA = Integer.MIN_VALUE,
maxB = Integer.MIN_VALUE,
maxC = Integer.MIN_VALUE;
int minA = Integer.MAX_VALUE,
minB = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; i++)
{
if (arr[i] > maxA)
{
maxC = maxB;
maxB = maxA;
maxA = arr[i];
}
else if (arr[i] > maxB)
{
maxC = maxB;
maxB = arr[i];
}
else if (arr[i] > maxC)
maxC = arr[i];
if (arr[i] < minA)
{
minB = minA;
minA = arr[i];
}
else if (arr[i] < minB)
minB = arr[i];
}
return Math.max(minA * minB * maxA,
maxA * maxB * maxC);
}
public static void main(String[] args)
{
int []arr = { 1 , - 4 , 3 , - 6 , 7 , 0 };
int n = arr.length;
int max = maxProduct(arr, n);
if (max == - 1 )
System.out.print( "No Triplet Exists" );
else
System.out.print( "Maximum product is " + max);
}
}
|
Python3
import sys
def maxProduct(arr, n):
if (n < 3 ):
return - 1
maxA = - sys.maxsize - 1
maxB = - sys.maxsize - 1
maxC = - sys.maxsize - 1
minA = sys.maxsize
minB = sys.maxsize
for i in range (n):
if (arr[i] > maxA):
maxC = maxB
maxB = maxA
maxA = arr[i]
else if (arr[i] > maxB):
maxC = maxB
maxB = arr[i]
else if (arr[i] > maxC):
maxC = arr[i]
if (arr[i] < minA):
minB = minA
minA = arr[i]
else if (arr[i] < minB):
minB = arr[i]
return max (minA * minB * maxA,
maxA * maxB * maxC)
arr = [ 1 , - 4 , 3 , - 6 , 7 , 0 ]
n = len (arr)
Max = maxProduct(arr, n)
if ( Max = = - 1 ):
print ( "No Triplet Exists" )
else :
print ( "Maximum product is" , Max )
|
C#
using System;
using System.Collections;
class GFG{
static int maxProduct( int []arr, int n)
{
if (n < 3)
return -1;
int maxA = Int32.MinValue,
maxB = Int32.MinValue,
maxC = Int32.MinValue;
int minA = Int32.MaxValue,
minB = Int32.MaxValue;
for ( int i = 0; i < n; i++)
{
if (arr[i] > maxA)
{
maxC = maxB;
maxB = maxA;
maxA = arr[i];
}
else if (arr[i] > maxB)
{
maxC = maxB;
maxB = arr[i];
}
else if (arr[i] > maxC)
maxC = arr[i];
if (arr[i] < minA)
{
minB = minA;
minA = arr[i];
}
else if (arr[i] < minB)
minB = arr[i];
}
return Math.Max(minA * minB * maxA,
maxA * maxB * maxC);
}
public static void Main( string [] args)
{
int []arr = { 1, -4, 3, -6, 7, 0 };
int n = arr.Length;
int max = maxProduct(arr, n);
if (max == -1)
Console.Write( "No Triplet Exists" );
else
Console.Write( "Maximum product is " + max);
}
}
|
Javascript
<script>
function maxProduct(arr , n)
{
if (n < 3)
return -1;
var maxA = Number.MIN_VALUE,
maxB = Number.MIN_VALUE,
maxC = Number.MIN_VALUE;
var minA = Number.MAX_VALUE,
minB = Number.MAX_VALUE;
for (i = 0; i < n; i++)
{
if (arr[i] > maxA)
{
maxC = maxB;
maxB = maxA;
maxA = arr[i];
}
else if (arr[i] > maxB)
{
maxC = maxB;
maxB = arr[i];
}
else if (arr[i] > maxC)
maxC = arr[i];
if (arr[i] < minA)
{
minB = minA;
minA = arr[i];
}
else if (arr[i] < minB)
minB = arr[i];
}
return Math.max(minA * minB * maxA,
maxA * maxB * maxC);
}
var arr = [ 1, -4, 3, -6, 7, 0 ];
var n = arr.length;
var max = maxProduct(arr, n);
if (max == -1)
document.write( "No Triplet Exists" );
else
document.write( "Maximum product is " + max);
</script>
|
Output
Maximum product is 168
Time Complexity: O(n)
Auxiliary Space: O(1)
Exercise:
1. Print the triplet that has a maximum product.
2. Find a minimum product of a triplet in the array.
Last Updated :
02 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...