题解
动态规划
因为有负数的存在,我们保存当前位置的最大乘积,和最小乘积,因为负数可以将最大乘积变最小,将最小变最大。
-
初试化结果 m a x _ r e s = M I N max\_res=MIN max_res=MIN,当前最大乘积 m a x _ n u m = 1 max\_num=1 max_num=1和当前最小乘积 m i n _ n u m = 1 min\_num=1 min_num=1。
-
遍历数组,遍历区间 [ 0 , n ) [0,n) [0,n):
- 若当前位置为负数
n
u
m
s
[
i
]
<
0
nums[i]<0
nums[i]<0:
- 交换最大乘积和最小乘积的值
- m a x _ n u m = m a x ( m a x _ n u m ∗ n u m s [ i ] , n u m s [ i ] ) max\_num=max(max\_num*nums[i],nums[i]) max_num=max(max_num∗nums[i],nums[i]),更新当前位置的最大乘积。
- m i n _ n u m = m i n ( m i n _ n u m ∗ n u m s [ i ] , n u m s [ i ] ) min\_num=min(min\_num*nums[i],nums[i]) min_num=min(min_num∗nums[i],nums[i]),更新当前位置的最小乘积。
- 更新结果 m a x _ r e s = m a x ( m a x _ n u m , m a x _ r e s ) max\_res=max(max\_num,max\_res) max_res=max(max_num,max_res)
- 若当前位置为负数
n
u
m
s
[
i
]
<
0
nums[i]<0
nums[i]<0:
-
返回 m a x _ r e s max\_res max_res
复杂度分析
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)
Python
class Solution:
def maxProduct(self, nums: List[int]) -> int:
n=len(nums)
max_res=-float("inf")
max_num=1
min_num=1
for i in range(n):
if(nums[i]<0):
max_num,min_num=min_num,max_num
max_num=max(max_num*nums[i],nums[i])
min_num=min(min_num*nums[i],nums[i])
max_res=max(max_num,max_res)
return max_res