I'm looking at the below solution, and spent hours and hours trying to understand why it works but couldn't figure it out. Assuming my understanding is correct that f1 stores the max length of positive nos and f2 stores the max length of negative nos, why is f1 reset to 0 when the number is negative and f2 is also zero?
class Solution {
func getMaxLen(_ nums: [Int]) -> Int {
var f1 = 0
var f2 = 0
var result = 0
for num in nums {
if num > 0 {
f1 += 1
if f2 > 0 {
f2 += 1
}
} else if num < 0 {
let temp = f1
if f2 > 0 {
f1 = f2 + 1
} else {
f1 = 0
}
f2 = temp + 1
} else {
f1 = 0
f2 = 0
}
result = max(result, f1)
}
return result
}
}
Read this article but it doesnt explain why f1 is reset to zero. Thank you so much in advance.
this understanding of yours is not completely correct. In your provided code -
Now, coming to your question :
f2 = 0 means length of a subarray ending at the current position with a negative product is 0, that means there hasn't been any negetive number previously to your current index. When your current number is negetive, if there is any negetive number present previously, then only it's possible to make a product positive, and as this is not the case for f2=0, so it's not possible to get a sub array ending at current index with positive product. That's why f1 becomes 0.