swiftalgorithmdynamic-programmingsliding-window

iOS Swift - Leetcode 1567. Maximum Length of Subarray With Positive Product


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.


Solution

  • Assuming my understanding is correct, that f1 stores the max length of positive nos and f2 stores the max length of negative nos

    this understanding of yours is not completely correct. In your provided code -

    f1 represents the length of the subarray ending at the current position with a positive product, and f2 (if non-zero) represents the length of a subarray ending at the current position with a negative product.


    Now, coming to your question :

    why is f1 reset to 0 when the number is negative and f2 is also zero?

    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.