Skip to content

Instantly share code, notes, and snippets.

@tkausch
Last active November 2, 2020 13:02
Show Gist options
  • Save tkausch/17bba0364fc5949138139b1ef6214a3e to your computer and use it in GitHub Desktop.
Save tkausch/17bba0364fc5949138139b1ef6214a3e to your computer and use it in GitHub Desktop.
Maximum sum subarray
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