Question:

Given an integer array, find three numbers whose product is maximum and output the maximum product.

给定整数数组,找出其最大值并输出最大乘积的三个数字。

Example:

  1. Input: [1,2,3]
  2. Output: 6
  1. Input: [1,2,3,4]
  2. Output: 24

Solution:

  1. /**
  2. * @param {number[]} nums
  3. * @return {number}
  4. */
  5. //此题需要考虑负数,比较最大三个数和最大数乘最小2个数的乘积
  6. var maximumProduct = function(nums) {
  7. nums.sort((a,b)=>a-b)
  8. let len = nums.length
  9. return Math.max(nums[0]*nums[1], nums[len-3]*nums[len-2])*nums[len-1]
  10. };