2708. 一个小组的最大实力值

2708. 一个小组的最大实力值


题目链接:2708. 一个小组的最大实力值

代码如下:

cpp 复制代码
class Solution
{
public:
	long long maxStrength(vector<int>& nums)
	{
		long long res = 1;
		int negativeCnt = 0, positiveCnt = 0, zeroCnt = 0;
		int maxNegative = INT_MIN;

		for (int i = 0; i < nums.size(); i++)
		{
			if (nums[i] < 0)
			{
				negativeCnt++;
				res *= nums[i];
				maxNegative = max(maxNegative, nums[i]);
			}
			else if (nums[i] == 0)
			{
				zeroCnt++;
			}
			else
			{
				res *= nums[i];
				positiveCnt++;
			}
		}

		//当数组仅有 1 个元素且为负数时,最大积为负数
		if (negativeCnt == 1 && zeroCnt == 0 && positiveCnt == 0)
		{
			return nums[0];
		}

		//当数组不包含正数,且负数元素小于等于 1 个时,最大积为 0
		if (negativeCnt <= 1 && positiveCnt == 0)
		{
			return 0;
		}

		//如果乘积为负数,则说明乘积中包含奇数个负数,此时将这个乘积除以最大负数则为最大积
		if (res < 0)
		{
			return res / maxNegative;
		}
		return res;
	}
};
相关推荐
沐怡旸2 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4165 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥7 小时前
C++ std::set
c++
侃侃_天下8 小时前
最终的信号类
开发语言·c++·算法
博笙困了8 小时前
AcWing学习——差分
c++·算法
青草地溪水旁9 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁9 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
感哥9 小时前
C++ std::vector
c++
zl_dfq9 小时前
C++ 之【C++11的简介】(可变参数模板、lambda表达式、function\bind包装器)
c++
每天回答3个问题9 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5