Maximum Product of Three Numbers

easy array sorting math

Problem

Find three numbers in the array whose product is maximum.

Inputnums = [-100,-98,-1,2,3,4]
Output39200
(-100)·(-98)·4 = 39200 beats 2·3·4.

def maximum_product(nums):
    nums = sorted(nums)
    return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1])
function maximumProduct(nums) {
  nums.sort((a, b) => a - b); const n = nums.length;
  return Math.max(nums[n-1]*nums[n-2]*nums[n-3], nums[0]*nums[1]*nums[n-1]);
}
int maximumProduct(int[] nums) {
    Arrays.sort(nums); int n = nums.length;
    return Math.max(nums[n-1]*nums[n-2]*nums[n-3], nums[0]*nums[1]*nums[n-1]);
}
int maximumProduct(vector& nums) {
    sort(nums.begin(), nums.end()); int n = nums.size();
    return max(nums[n-1]*nums[n-2]*nums[n-3], nums[0]*nums[1]*nums[n-1]);
}
Time: O(n log n) Space: O(1)