628. Maximum Product of Three Numbers(Solution || Leetcode easy || Java)
1 min readNov 14, 2022
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 <= 104
-1000 <= nums[i] <= 1000
SOLUTION:
class Solution {
public int maximumProduct(int[] nums) {
//find the three largest values from the array
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int max3 = Integer.MIN_VALUE;
//find two minimum values from the array beacuse minimum could be
//-100 and -99 and multiplying both these minimum give us positive number
//then multiply this number with the largest element, that will give us our
//answer
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
int i = 0;
while(i < nums.length){
if(nums[i] >= max1){
max3 = max2;
max2 = max1;
max1 = nums[i];
}
else if(nums[i] >= max2){
max3 = max2;
max2 = nums[i];
}
else if(nums[i] >= max3){
max3 = nums[i];
}
if(nums[i] <= min1){
min2 = min1;
min1 = nums[i];
}
else if(nums[i] <= min2){
min2 = nums[i];
}
i++;
}
return Math.max(min1*min2*max1, max1*max2*max3);
}
}
Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.