Maximum Product Subarray

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input:
 [2,3,-2,4]

Output:
6
Explanation:
 [2,3] has the largest product = 6.

Example 2:

Input:
 [-2,0,-1]

Output:
 0

Explanation:
 The result cannot be 2, because [-2,-1] is not a subarray.

分析

2个负数相乘可以得到最大值,需要存储当前最小的数。

可以直接交换curMin和curMax

当前状态需要考虑前面的几步,而无法从前一个数直接决定:比如前面数可能取了负数成了最小,但遇到下一个负数成了最大,所以前数需要保留负数态。如果只考虑一个状态,前数会直接取正数,导致得不到最大。

所以这里设置两个全局变量以便考虑前面几个的状态,同时注意curMax和curMin都必须包含当前数,意味着下一步使用这俩变量时候,保证了数组的连续性。

答案

python

负负得正,所以2个数组,一个存最大一个存最小

因为只和前面状态min,max相关,并且当前态就能比较出res,只要设置这3个变量即可

Last updated

Was this helpful?