编程之美 子数组的最大乘积

#include <iostream>
#include <limits.h>
using namespace std;

int multiWithoutN(int *P, int length, int key)
{
	int result = 1;
	bool first = true;  //引入first变量进行key值的排除。  
	for (int i = 0; i < length; i++)
	{
		if (first && P[i] == key)
		{
			first = false;
		}
		else
		{
			result *= P[i];
		}
	}
	return result;
}
//数组中去除N以后,各元素的乘积
int calculate(int *P, int length)
{
	int plus_Count = 0, minus_Count = 0, zero_Count = 0;
	int fab_min_minus, fab_max_minus, fab_min_plus;
	int multi =1;

	fab_min_minus = INT_MIN;
	fab_max_minus = -1;
	fab_min_plus = INT_MAX;
	for (int i = 0; i < length; i++)
	{
		multi *= P[i];
		if (P[i] > 0)
		{
			plus_Count++;
			if (P[i] < fab_min_plus)
			{
				fab_min_plus = P[i];
			}
		}
		else if (P[i] < 0)
		{
			minus_Count++;
			if (P[i] > fab_min_minus)
			{
				fab_min_minus = P[i];
			}
			else if (P[i] < fab_max_minus)
			{
				fab_max_minus = P[i];
			}
		}
		else
		{
			zero_Count++;
		}
	}
	
	if (zero_Count > 1)
	{
		return 0;
	}
	else if (zero_Count ==1)
	{
		int q = multiWithoutN(P, length, 0);
		if (q > 0)
		{
			return q;
		}
		else
			return 0;
	}
	else{
		if (minus_Count%2 != 0)
		{
			return multiWithoutN(P, length, fab_min_minus);
		}
		else{
			if (plus_Count == 0)
				return multiWithoutN(P, length, fab_max_minus);
			else 
				return multiWithoutN(P, length, fab_min_plus);
		}
	}
}

int main()
{
	int p[] = {-2, -3, -5, -6, -9, -7};
	int length = 6;
	int m = calculate(p, length);
	cout<<m<<endl;
}

 

PS:感谢锟仔的提醒。


    原文作者:yeepom
    原文地址: https://blog.csdn.net/yeepom/article/details/8627071
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞