Last active
November 2, 2020 13:02
-
-
Save tkausch/17bba0364fc5949138139b1ef6214a3e to your computer and use it in GitHub Desktop.
Maximum sum subarray
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 maxSubArray(_ nums: [Int]) -> Int { | |
guard nums.count > 0 else { | |
return Int.min | |
} | |
var bestEndingSum = nums.first! | |
var maxSum = nums.first! | |
for num in nums[1..<nums.endIndex] { | |
bestEndingSum = max(bestEndingSum + num, num) | |
if bestEndingSum > maxSum { | |
maxSum = bestEndingSum | |
} | |
} | |
return maxSum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment