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.