
问题
给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
输入: [1,2,3]
输出: 6
输入: [1,2,3,4]
输出: 24
注意:
给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。
输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Input: [1,2,3]
Output: 6
Input: [1,2,3,4]
Output: 24
Note:
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won’t exceed the range of 32-bit signed integer.
示例
public class Program { public static void Main(string[] args) { int[] nums = null; nums = new int[] { -4, 12, 9, -20 }; var res = MaximumProduct(nums); Console.WriteLine(res); Console.ReadKey(); } private static int MaximumProduct(int[] nums) { //先排序 Array.Sort(nums); //记录数组长度 int length = nums.Length; //该题主要考查数组中包含负数的情况 //如果全为正数,排序后输出后3位的乘积即可 //否则,最大值一定在最小的2个负数和最大数的乘积、后3位值的乘积中产生 //直接比较它们的大小输出即可 //先存下数组后3位值的乘积 int product = nums[length - 1] * nums[length - 2] * nums[length - 3]; //取前2位和最后1位的乘积、后3位值的乘积中的最大值 product = Math.Max(product, nums[length - 1] * nums[1] * nums[0]); //输出这个最大值 return product; } }
以上给出1种算法实现,以下是这个案例的输出结果:
960
分析:
显而易见,以上算法的时间复杂度基于 Array.Sort() 所使用的排序算法。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3726。