1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- package kata
- func isDegeneratePositive(numbers []int) bool {
- for _, n := range numbers {
- if n < 0 {
- return false
- }
- }
- return true
- }
- func isDegenerateNegative(numbers []int) bool {
- for _, n := range numbers {
- if n > 0 {
- return false
- }
- }
- return true
- }
- func sum(s []int) int {
- res := 0
- for _, n := range s {
- res += n
- }
- return res
- }
- func MaximumSubarraySum(numbers []int) int {
- // Covers the empty case as well.
- if isDegeneratePositive(numbers) {
- return sum(numbers)
- }
- // Would cover the empty case as well, but it was handled above.
- if isDegenerateNegative(numbers) {
- return 0
- }
- max := 0
- for i := 0; i < len(numbers); i++ {
- for j := i; j <= len(numbers); j++ {
- sliced := numbers[i:j]
- candidate := sum(sliced)
- if candidate > max {
- max = candidate
- }
- }
- }
- return max
- }
|