Maximum Subarray in Go

Published on 31 October 2025 (Updated: 31 October 2025)

Welcome to the Maximum Subarray in Go page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

package main

import (
	"fmt"
	"os"
	"strconv"
	"strings"
)

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func main() {
	if len(os.Args) < 2 || strings.TrimSpace(os.Args[1]) == "" {
		fmt.Println(`Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"`)
		return
	}
	input := strings.Join(os.Args[1:], "")
	parts := strings.Split(input, ",")
	nums := make([]int, len(parts))

	for i, p := range parts {
		p = strings.TrimSpace(p)
		n, _ := strconv.Atoi(p)
		nums[i] = n

	}

	maxSum := nums[0]
	blockSum := nums[0]

	for i := 1; i < len(nums); i++ {
		blockSum = max(nums[i], blockSum+nums[i])
		if maxSum < blockSum {
			maxSum = blockSum

		}

	}
	fmt.Println(maxSum)

}

Maximum Subarray in Go was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.