628. Maximum Product of Three Numbers(Solution || Leetcode easy || Java)
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) {
//first sort the arrays
Arrays.sort(nums);
//initialise a variable to return and give it value 1 rather than 0 because, we are going to multiply numbers in it
int ans = 1;
//as the array is sorted last three numbers are the greatest
for(int i = nums.length — 1; i > nums.length — 4; i — ){
ans *= nums[i];
}
//as the array could be {-100,-99,3,5} hence we also need to consider the first 2 numbers
int mightAns = nums[nums.length-1] * nums[0] * nums[1];
if(ans < mightAns){
return mightAns;
}
return ans;
}
}
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.