MaxProductOfThree

Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R)

My C++ solution

#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

int solution(vector<int> &A) 
{
   if ( A.size()==3 )
      return A[0] * A[1] * A[2];

   std::sort(A.rbegin(), A.rend());

   int size = A.size();

   int triplet1 = A[0] * A[1] * A[2];
   int triplet2 = A[size - 1] * A[size - 2] * A[0];
   int triplet3 = A[size - 2] * A[size - 3] * A[0];
   int triplet4 = A[size - 1] * A[size - 3] * A[0];

   return max(triplet1, max(triplet2, max(triplet3, triplet4)));
      
}
Comments