Skip to content

Latest commit

 

History

History
122 lines (105 loc) · 2.42 KB

628.三个数的最大乘积.md

File metadata and controls

122 lines (105 loc) · 2.42 KB

628. 三个数的最大乘积

url

题目

给你一个整型数组 nums ,在数组中找出由三个数组成的最大乘积,并输出这个乘积。

输入:nums = [1,2,3]
输出:6
输入:nums = [1,2,3,4]
输出:24
输入:nums = [-1,-2,-3]
输出:-6

方法

code

js

let maximumProduct = nums => {
    let minValue = -Infinity;
    let max1 = minValue, max2 = minValue, max3 = minValue;
    let min1 = -minValue, min2 = -minValue;
    nums.forEach(n => {
        if (n > max1) {
            max3 = max2;
            max2 = max1;
            max1 = n;
        } else if (n > max2) {
            max3 = max2;
            max2 = n;
        } else if (n > max3) {
            max3 = n;
        }
        if (n < min1) {
            min2 = min1;
            min1 = n;
        } else if (n < min2) {
            min2 = n;
        }
    });
    return Math.max(max1 * max2 * max3, max1 * min1 * min2);
};
console.log(maximumProduct([1, 2, 3]));
console.log(maximumProduct([1, 2, 3, 4]));

go

func maximumProduct(nums []int) int {
	INT_MAX := int(^uint((0)) >> 1)
	INT_MIN := ^INT_MAX
	max1, max2, max3 := INT_MIN, INT_MIN, INT_MIN
	min1, min2 := INT_MAX, INT_MAX
	for _, num := range nums {
		if num > max1 {
			max3 = max2
			max2 = max1
			max1 = num
		} else if num > max2 {
			max3 = max2
			max2 = num
		} else if num > max3 {
			max3 = num
		}
		if num < min1 {
			min2 = min1
			min1 = num
		} else if num < min2 {
			min2 = num
		}
	}
	return max4(max1 * max2 * max3, max1 * min1 * min2)
}
func max4(a int, b int) int {
	if a < b {
		return b
	} else {
		return a
	}
}

java

class Solution {
    public int maximumProduct(int[] nums) {
        int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE,min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
        for (int n : nums) {
            if (n > max1) {
                max3 = max2;
                max2 = max1;
                max1 = n;
            } else if (n > max2) {
                max3 = max2;
                max2 = n;
            } else if (n > max3) {
                max3 = n;
            }
            if (n < min1) {
                min2 = min1;
                min1 = n;
            } else if (n < min2) {
                min2 = n;
            }
        }
        return Math.max(max1*max2*max3, max1*min1*min2);
    }
}