题目如下:
Given an array of integers
nums
, find the maximum length of a subarray where the product of all its elements is positive.A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4] Output: 4 Explanation: The array nums already has a positive product of 24.Example 2:
Input: nums = [0,1,-2,-3,-4] Output: 3 Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6. Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.Example 3:
Input: nums = [-1,-2,-3,0,1] Output: 2 Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].Example 4:
Input: nums = [-1,2] Output: 1Example 5:
Input: nums = [1,2,3,5,-6,4,0,10] Output: 4Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
解题思路:根据题目要求,0是不能被计算在子数组之内的,因此可以理解成0比nums分成了若干个子数组。对于每个子数组,我们只需要从左往右遍历,记录当前负数的个数以及第一次出现负数为奇数时候的下标。这样的话,如果当前负数的个数是偶数,那么这一段子数组的乘积为正数;而如果是奇数,则与第一次出现负数为奇数时组成的这一段子数组中有偶数个负数,其成绩也为正数。
代码如下:
class Solution(object): def getMaxLen(self, nums): """ :type nums: List[int] :rtype: int """ last_neg_odd = None neg_count = 0 start = None res = 0 for i in range(len(nums)): if nums[i] == 0: last_neg_odd = None neg_count = 0 start = None continue elif start == None: start = i if nums[i] < 0:neg_count += 1 if neg_count % 2 == 0: res = max(res,i - start + 1) else: if last_neg_odd == None: last_neg_odd = i else: res = max(res, i - last_neg_odd) return res