Skip to content

Instantly share code, notes, and snippets.

@mAlishera
Created January 16, 2020 15:44
Show Gist options
  • Save mAlishera/d34486667b7383cc0af943bb6b5073d1 to your computer and use it in GitHub Desktop.
Save mAlishera/d34486667b7383cc0af943bb6b5073d1 to your computer and use it in GitHub Desktop.
4 ms 4.3 MB
func maxSubArray(nums []int) int {
if len(nums) <= 0 {
return 0
}
arr := []int{}
sum := 0
max := nums[0]
for i := 0; i < len(nums); i++ {
if nums[i] > max {
max = nums[i]
}
if nums[i] < 0 && !checkBackwardForPositive(nums[i], arr) {
arr = []int{}
sum = 0
continue
}
arr = append(arr, nums[i])
sum += nums[i]
if sum > max {
max = sum
}
}
return max
}
func checkBackwardForPositive(v int, arr []int) bool {
sum := v
for i := (len(arr) - 1); i >= 0; i-- {
sum += arr[i]
if sum > 0 {
return true
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment