Created
November 2, 2020 13:58
-
-
Save tkausch/d241c688feb952112423acdc8590273f to your computer and use it in GitHub Desktop.
Maximum Product Subarray (smarter)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func maxProduct(_ nums: [Int]) -> Int { | |
guard nums.count > 0 else { | |
return 0 | |
} | |
var maximum = nums.first! | |
var maxPositivEnding = nums.first! | |
var minNegativeEnding = nums.first! | |
for num in nums.dropFirst() { | |
if num > 0 { | |
maxPositivEnding = max(num, num * maxPositivEnding) | |
minNegativeEnding = min(num, num * minNegativeEnding) | |
} else { | |
let t = maxPositivEnding | |
maxPositivEnding = max(num, num * minNegativeEnding ) | |
minNegativeEnding = min(num, num * t) | |
} | |
maximum = max(maximum, maxPositivEnding) | |
} | |
return maximum | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment