You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
大数的一般处理思路就是分割数组, 将大的问题化成一个个小问题再一一解决.
以0位分割点, 分割生成不同的子数组,
分别计算子数组中的负数个数
偶数个数的负数, 直接输出数组长度,
奇数个数的负数, 找出这个数组中左右分别第一个负数, 输出长度 减去这个index.
将这个结果收集起来, 拿到最大数.
答案
/** * @param {number[]} nums * @return {number} */vargetMaxLen=function(nums){// length from high to lowletmax=0letsz=nums.lengthletarrSplit0=[]lettemp=[]nums.forEach(e=>{if(e==0){arrSplit0.push(temp)temp=[]}else{temp.push(e)}})arrSplit0.push(temp)arrSplit0=arrSplit0.map(arr=>{letneg=0arr.forEach(e=>{if(e<0){neg++}})if(neg%2==0){returnarr.length}else{for(leti=0,j=arr.length-1;i<j;i++,j--){if(arr[i]<0||arr[j]<0){returnarr.length-i-1}}return0}})returnMath.max(...arrSplit0)};
The text was updated successfully, but these errors were encountered:
plh97
changed the title
1567. Maximum Length of Subarray With Positive Product
[LeetCode] 1567. Maximum Length of Subarray With Positive Product
Oct 6, 2020
一道大数题目. 找出最长的数组区间, 这个区间内的数相乘为正数
大数的一般处理思路就是分割数组, 将大的问题化成一个个小问题再一一解决.
以0位分割点, 分割生成不同的子数组,
分别计算子数组中的负数个数
偶数个数的负数, 直接输出数组长度,
奇数个数的负数, 找出这个数组中左右分别第一个负数, 输出长度 减去这个index.
将这个结果收集起来, 拿到最大数.
答案
The text was updated successfully, but these errors were encountered: