From 4b7c6e8712e4524f224a8be205ac64fb1ce98208 Mon Sep 17 00:00:00 2001 From: dharni0607 Date: Tue, 23 Jul 2019 00:10:52 +0530 Subject: [PATCH] O(n) solution for maximum contiguos subarray sum --- other/maxSubarraySum.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 other/maxSubarraySum.go diff --git a/other/maxSubarraySum.go b/other/maxSubarraySum.go new file mode 100644 index 000000000..a336dd378 --- /dev/null +++ b/other/maxSubarraySum.go @@ -0,0 +1,30 @@ +/* O(n) solution, for calculating +maximum contiguous sum in the given array. */ + +package main + +import ( + "fmt" +) + +func Max(x int, y int) int { + if x < y { + return y + } + return x +} + +func maxSubarraySum(array []int) int { + var currentMax int = 0 + var maxTillNow int = 0 + for i := 0; i < len(array); i++ { + currentMax = Max(array[i], currentMax + array[i]) + maxTillNow = Max(maxTillNow, currentMax) + } + return maxTillNow +} + +func main() { + array := []int{-2, -5, 6, 0, -2, 0, -3, 1, 0, 5, -6} + fmt.Println("Maximum contiguous sum: ", maxSubarraySum(array)) +}