How to find three consecutive numbers with the largest sum in a slice of integers in Go

1 Answer

0 votes
package main

import (
	"errors"
	"fmt"
)

// findMaxSumOfThree finds 'k' consecutive numbers with the largest sum in a slice.
// It returns the maximum sum, the corresponding subslice of numbers, and an error if invalid.
func findMaxSumOfThree(numbers []int, k int) (int, []int, error) {
	// Validate input parameters
	if k <= 0 || len(numbers) < k {
		return 0, nil, errors.New("slice length is smaller than k or k is invalid")
	}

	// Compute the sum of the first window of size k
	currentSum := 0
	for i := 0; i < k; i++ {
		currentSum += numbers[i]
	}

	maxSum := currentSum
	maxStartIndex := 0

	// Slide the window across the rest of the slice:
	// Subtract the element leaving the window on the left, and add the new element on the right.
	for i := k; i < len(numbers); i++ {
		currentSum = currentSum - numbers[i-k] + numbers[i]

		if currentSum > maxSum {
			maxSum = currentSum
			maxStartIndex = i - k + 1
		}
	}

	// Extract and return the sequence with the maximum sum
	resultNumbers := numbers[maxStartIndex : maxStartIndex+k]
	return maxSum, resultNumbers, nil
}

func main() {
	numbers := []int{4, 2, 0, 8, 7, 5, 1, 3, 9, 6}
	k := 3

	sum, result, err := findMaxSumOfThree(numbers, k)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Printf("Largest sum: %d\n", sum)
	fmt.Printf("Numbers: %v\n", result)
}


/*
run:

Largest sum: 20
Numbers: [8 7 5]

*/

 



answered Oct 30 by avibootz

Related questions

...