Print product of maximum triplet

Share

Problem: For a given array of positive or negative integers, find maximum product of a triplet.

Problem Explanation: For a given array a ={1, -2, 3, 4, -5},  if we multiply  -2, 4, and -5 it will be a maximum product of a triplet. Hence, output will be 40.

Java Implementation

public void maxTripletProduct(int arr[]) {
    int maxA, maxB, maxC, minA, minB;
    maxA = Integer.MIN_VALUE;
    maxB = Integer.MIN_VALUE;
    maxC = Integer.MIN_VALUE;

    minA = Integer.MAX_VALUE;
    minB = Integer.MAX_VALUE;

    for (int i = 0; i < arr.length; 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]; 
        } 
   } 
   
   int possibleMaxValue1 = maxA * maxB * maxC; 
   int possibleMaxValue2 = minA * minB * maxA; 

   System.out.println(possibleMaxValue1 > 
                      possibleMaxValue2 ? possibleMaxValue1 : possibleMaxValue2);
}

TimeComplexity: O(n)

Note: If you find any other better way to approach to this problem or you find any issue/error in above code snippets/approaches – please share it in the comments section below and get a chance to enrol free of cost for an online Live Data Structure and Algorithm course (specially designed for interview preparation for software companies like Amazon, Google, Facebook, FlipKart, SnapDeal, HealthKart…)