C#LeetCode刷题之#628-三个数的最大乘积( Maximum Product of Three Numbers)

问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3726 访问。

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

输入: [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.


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3726 访问。

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种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3726 访问。

960

分析:

显而易见,以上算法的时间复杂度基于 Array.Sort() 所使用的排序算法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值