Skip to content

Instantly share code, notes, and snippets.

@MorrisLaw
Last active January 21, 2022 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MorrisLaw/fd181aaacb16082cf7af58dcada3ecf3 to your computer and use it in GitHub Desktop.
Save MorrisLaw/fd181aaacb16082cf7af58dcada3ecf3 to your computer and use it in GitHub Desktop.
time complexity is O(n) because we do at most, one iteration through the array where n is the length of the array. Space complexity is constant since we have an input array and 3 variables we are using (curr, max and i)
import "math"
func maxSubArray(nums []int) int {
if nums == nil { return 0 }
curr := nums[0]
max := curr
for i := 1; i < len(nums); i++ {
curr = int(math.Max(float64(curr + nums[i]), float64(nums[i])))
if curr > max {
max = curr
}
}
return max
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment