Golang program to find maximum sum of a subarray with length k


In this article we are going to understand how to use methods naming brute-force, sliding window and prefix sum methods of golang to find the maximum sum of a subarray with length k. We will also discuss the Algorithm for each method and provide code Examples to demonstrate their implementation.

Syntax

func len(v Type) int

The len() function is used to get the length of a any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable.

Example 1

The first Example to find maximum sum of a subarray with length k is Brute-Force Method.

package main

import (
   "fmt"
   "math"
)

func maxSumBruteForce(arr []int, k int) int {
   n := len(arr)
   maxSum := math.MinInt64

   for i := 0; i <= n-k; i++ {
      sum := 0

      for j := i; j < i+k; j++ {
         sum += arr[j]
      }

      if sum > maxSum {
         maxSum = sum
      }
   }
   return maxSum
}

func main() {
   x := []int{1, 2, 3, 4, 5}
   fmt.Println("The given array of integers is:", x)
   var num int = 5
   result := maxSumBruteForce(x, num)
   fmt.Println("The max sum is:", result)
}

Output

The given array of integers is: [1 2 3 4 5]
The max sum is: 15

Example 2

In this Example we will write a go language program to find the maximum sum of a subarray having k number of elements by using prefix sum method.

package main

import (
   "fmt"
   "math"
)

func maxSumPrefixSum(arr []int, k int) int {
   n := len(arr)
   maxSum := math.MinInt64
   prefixSum := make([]int, n+1)

   for i := 1; i <= n; i++ {
      prefixSum[i] = prefixSum[i-1] + arr[i-1]
   }

   for i := k; i <= n; i++ {
      sum := prefixSum[i] - prefixSum[i-k]

      if sum > maxSum {
         maxSum = sum
      }
   }
   return maxSum
}

func main() {
   x := []int{1, 2, 3, 4, 5, 6}
   fmt.Println("The given array of integers is:", x)
   var num int = 6
   result := maxSumPrefixSum(x, num)
   fmt.Println("The max sum is:", result)
}

Output

The given array of integers is: [1 2 3 4 5 6]
The max sum is: 21

Conclusion

In this article, we explored three different methods to find the maximum sum of a subarray of a given length k in Golang. Here we have used two methods viz. The brute-force method and prefix sum method. The brute force method has a time complexity of O(nk), while prefix sum methods have a time complexity of O(n). The prefix sum methods is more efficient than the brute-force method, as it avoids unnecessary calculations.

Updated on: 05-Apr-2023

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements