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 小时前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴3 小时前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt00117 小时前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾21 小时前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you1 天前
constexpr函数
c++
凡人叶枫1 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫1 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss1 天前
BRpc使用
c++·rpc
-森屿安年-1 天前
63. 不同路径 II
c++·算法·动态规划
chase_my_dream1 天前
Cartographer详细讲解
c++·人工智能·自动驾驶