给定一个长度为N的整数数组,计算任意(N-1)个数的组合中乘积最大的一组,算法的时间复杂度为O(N)

本文介绍了一种算法,通过分析数组中正数、负数和零的数量来决定移除哪个元素可以使剩余元素的乘积最大化。提供了C#实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分析与解法

遍历一遍数组,求出数组中正数(+),负数(-)和0的个数,从而判断N个数乘积的正负性,依此判断是去掉0,还是最小的负数,还是最大的负数,还是最小的正数来得到目标的N-1个数,使乘积最大。

例如:集合全为负数时,去掉最小负数;全为正数时去掉最小正数;等等还有很多种情况.

主要要考虑集合中0的个数与集合中负数的个数以及全为负数的情况。


C# Codes


namespace ConsoleApp2010
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine(FindItem(new int[] { -1, -2, -3, -4}));
            System.Console.ReadKey();
        }


        static int FindItem(int[] array)
        {
            int length = array.Length;
            int negativeNum = 0;
            int maxNegative = 0;
            int minNegative = 0;
            int minPositive = 0;
            int zeroNum = 0;


            for (int i = 0; i < length; i++)
            {
                if (array[i] < 0)
                {
                    negativeNum++;


                    if (maxNegative == 0 || maxNegative < array[i])
                    {
                        maxNegative = array[i];
                    }


                    if (minNegative == 0 || minNegative > array[i])
                    {
                        minNegative = array[i];
                    }
                }
                else if (array[i] == 0)
                {
                    zeroNum++;
                }
                else
                {
                    if (minPositive == 0 || minPositive > array[i])
                    {
                        minPositive = array[i];
                    }
                }
            }


            int result;


            if (zeroNum > 1)
            {
                result = 0;
            }
            else if (zeroNum == 1)
            {
                if (negativeNum % 2 == 0)
                {
                    result = 0;
                }
                else
                {
                    result = maxNegative;
                }
            }
            else
            {
                if (negativeNum % 2 == 0)
                {
                    if (minPositive != 0)
                    {
                        result = minPositive;
                    }
                    else
                    {
                        result = minNegative;
                    }
                }
                else
                {
                    result = maxNegative;
                }
            }


            return result;
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值