628.三数目的最大与最小(628.MaximumProductofThreeNumbers)javascript

原创
小哥 3年前 (2022-11-16) 阅读数 8 #大杂烩

给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.

示例 1:

输入: [1,2,3]
输出: 6

Example 1:

Input: nums = [1,2,3]
Output: 6

示例 2:

输入: [1,2,3,4]
输出: 24

Example 2:

Input: nums = [1,2,3,4]
Output: 24

Example 3:

Input: nums = [-1,-2,-3]
Output: -6

var maximumProduct = function (nums) {
    //1.先将数组进行升序排列
    nums.sort(function (a, b) {
        return a - b;
    });
    let len=nums.length;
    //2.有两种情况三个数相乘数值最大
    //(1)三个正数相乘,最后三个数乘积最大
    a=nums[len-1]*nums[len-2]*nums[len-3];
    //(2)最小的两个负数相乘,再乘以最后一个正数
    b=nums[0]*nums[1]*nums[len-1];
    //两者比较,谁大取谁
    return a>b?a:b;
};

执行用时:136 ms, 在所有 JavaScript 提交中击败了73.83%的用户
内存消耗:42 MB, 在所有 JavaScript 提交中击败了34.42%的用户

题目来自: https://leetcode-cn.com/problems/maximum-product-of-three-numbers/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

上一篇:正数取反 下一篇:面试问题总结2