from typing import List
class Solution:
def maxStrength(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
nums.sort()
product = 1
negative_count = 0
non_zero_count = 0
max_positive = float('-inf')
for num in nums:
if num != 0:
product *= num
non_zero_count += 1
if num > 0:
max_positive = max(max_positive, num)
if num < 0:
negative_count += 1
if non_zero_count == 0:
return 0
if product > 0:
return product
else:
if negative_count % 2 != 0:
# 如果乘积为负数且负数的个数为奇数,则去除绝对值最小的负数
smallest_negative = nums[negative_count - 1]
product //= smallest_negative
# 如果去除负数后没有非零元素,则返回最大正数或0
if product == 1:
return max_positive if max_positive != float('-inf') else 0
return product
# 测试用例
solution = Solution()
print(solution.maxStrength([0, -1])) # 输出应为 0
print(solution.maxStrength([-3, 0, 1])) # 输出应为 1
以下是求解思路:
-
特殊情况处理:
- 如果数组长度为1,直接返回该元素,因为只有一个元素时,最大实力值就是该元素本身。
-
排序数组:
- 对数组进行排序,以便后续处理负数和正数时更加方便。
-
初始化变量:
product
:用于存储所有非零元素的乘积。negative_count
:用于统计负数的个数。non_zero_count
:用于统计非零元素的个数。max_positive
:用于记录数组中的最大正数,初始值为负无穷大。
-
遍历数组:
- 对于每个元素:
- 如果元素不为零,将其乘入
product
,并增加non_zero_count
。 - 如果元素为正数,更新
max_positive
。 - 如果元素为负数,增加
negative_count
。
- 如果元素不为零,将其乘入
- 对于每个元素:
-
处理特殊情况:
- 如果数组中没有非零元素,返回0。
-
计算最终结果:
- 如果
product
为正数,直接返回product
。 - 如果
product
为负数且负数的个数为奇数,去除绝对值最小的负数(因为数组已排序,负数部分的最后一个元素即为绝对值最小的负数),更新product
。 - 如果去除负数后
product
为1,返回max_positive
或0(如果没有正数)。 - 否则,返回
product
。
- 如果