Problem : https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/
Positive A * Positive B -> Positive C
Negative A * Negative B -> Positive C
Keep tracking positive and negative product result sub-array length end by current number.
Reset sub-array length when encounter '0'
class Solution {
fun getMaxLen(nums: IntArray): Int {
var positiveSoFar = 0
var negativeSoFar = 0
var result = 0
for (n in nums) {
if (n > 0) {
positiveSoFar += 1
negativeSoFar = if (negativeSoFar > 0) negativeSoFar + 1 else 0
} else if (n < 0) {
val prePositiveSoFar = positiveSoFar
positiveSoFar = if (negativeSoFar > 0 ) negativeSoFar + 1 else 0
negativeSoFar = prePositiveSoFar + 1
} else {
positiveSoFar = 0
negativeSoFar = 0
}
result = maxOf(result, positiveSoFar)
}
return result
}
}
No comments:
Post a Comment