Appearance
题目描述
https://leetcode.cn/problems/maximum-product-of-three-numbers
给你一个整型数组 nums ,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
示例 1:
输入:nums = [1,2,3]
输出:6
示例 2:
输入:nums = [1,2,3,4]
输出:24
示例 3:
输入:nums = [-1,-2,-3]
输出:-6
提示:
- 3 <= nums.length <= 10^4
- -1000 <= nums[i] <= 1000
思路
排序,找出最小的两个数,是负数的话会相乘得正。 再找出最大的三个数。 然后比较他们相乘的结果,取大的值。
Sort 的时间复杂度 o(nlogn) ,也可以使用一趟扫描法找出这5个数
csharp
public class Solution {
public int MaximumProduct(int[] nums) {
//思路,排序,找出最小的两个数和最大的三个数
Array.Sort(nums);
int n = nums.Length;
int min1 = nums[0];
int min2 = nums[1];
int max1 = nums[n-3];
int max2 = nums[n-2];
int max3 = nums[n-1];
return Math.Max(min1*min2*max3, max1*max2*max3);
}
}
AlgoPress