Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
Input: nums = [1,2,3]
Output: 6
Example 2:
Input: nums = [1,2,3,4]
Output: 24
Example 3:
Input: nums = [-1,-2,-3]
Output: -6
Constraints:
3 <= nums.length <= 1041000 <= nums[i] <= 1000Maximum Product of Three Numbers - LeetCode
Maximum product of a triplet (subsequence of size 3) in array - GeeksforGeeks
class Solution {
public:
int maximumProduct(vector<int>& nums) {
int n = nums.size();
if(n==3)
return nums[0]*nums[1]*nums[2];
int max1,max2,max3,min1,min2;
max1 = max2 = max3 = INT_MIN;
min1 = min2 = INT_MAX;
for(int ele:nums)
{
if(ele>max1)
{
max3 = max2;
max2 = max1;
max1 = ele;
}
else if(ele>max2)
{
max3 = max2;
max2 = ele;
}
else if(ele>max3)
{
max3 = ele;
}
if(ele<min1)
{
min2 = min1;
min1 = ele;
}
else if(ele<min2)
{
min2 = ele;
}
}
return max(max1*max2*max3,min1*min2*max1);
}
};