k.go 826 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package kata
  2. func isDegeneratePositive(numbers []int) bool {
  3. for _, n := range numbers {
  4. if n < 0 {
  5. return false
  6. }
  7. }
  8. return true
  9. }
  10. func isDegenerateNegative(numbers []int) bool {
  11. for _, n := range numbers {
  12. if n > 0 {
  13. return false
  14. }
  15. }
  16. return true
  17. }
  18. func sum(s []int) int {
  19. res := 0
  20. for _, n := range s {
  21. res += n
  22. }
  23. return res
  24. }
  25. func MaximumSubarraySum(numbers []int) int {
  26. // Covers the empty case as well.
  27. if isDegeneratePositive(numbers) {
  28. return sum(numbers)
  29. }
  30. // Would cover the empty case as well, but it was handled above.
  31. if isDegenerateNegative(numbers) {
  32. return 0
  33. }
  34. max := 0
  35. for i := 0; i < len(numbers); i++ {
  36. for j := i; j <= len(numbers); j++ {
  37. sliced := numbers[i:j]
  38. candidate := sum(sliced)
  39. if candidate > max {
  40. max = candidate
  41. }
  42. }
  43. }
  44. return max
  45. }