Max Sum of K Window

Max Sum of K Window

Problem Statement

Given an array and an integer K, return the maximum sum that can be obtained by picking up K elements consecutively.

  • Example 1:
    • Input:
      • arr= [-1, 2, 3, 3, 4, 5, -1], K= 4
    • Output:15
    • Explanation:
      • For the given array [-1, 2, 3, 3, 4, 5, -1] and K=4, the maximum sum that can be obtained by picking up 4 elements consecutively is achieved by selecting elements [3, 3, 4, 5], resulting in a sum of 15.
  • Example 2:
    • Input:
      • arr= [2, -5, 6, 1, -2, 4, 3], K= 3
    • Output: 11
    • Explanation:
      • For the array [2, -5, 6, 1, -2, 4, 3] and K=3, the maximum sum that can be obtained by picking up 3 elements consecutively is achieved by selecting elements [6, 1, -2], resulting in a sum of 11.

Golang Solution

package main

import (
	"fmt"
)

func maxSumOfKWindow(arr []int, k int) int {
	if len(arr) == 0 || k <= 0 || k > len(arr) {
		return 0
	}

	currentSum := 0
	for i := 0; i < k; i++ {
		currentSum += arr[i]
	}

	maxSum := currentSum

	left := 0
	right := k - 1
	for right < len(arr)-1 {
		currentSum = currentSum - arr[left]
		left++
		right++
		currentSum = currentSum + arr[right]
		maxSum = max(currentSum, maxSum)
	}
	return maxSum
}

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

func main() {
	arr := []int{-1, 2, 3, 3, 4, 5, -1}
	k := 4
	answer := maxSumOfKWindow(arr, k)

	fmt.Printf("maxSumOfKWindow answer=%d\n", answer)
}

Output

maxSumOfKWindow answer=15

Test Cases

Positive Case

arr := []int{1, 2, 3, 4, 5}
k := 2
// Expected: 9 (4+5)

Negative Numbers

arr := []int{-1, -2, -3, -4, -5}
k := 2
// Expected: -3 (-1+-2)

Invalid Cases

arr := []int{}
k := 3
// Expected: 0 (empty array)

arr := []int{1, 2}
k := 0
// Expected: 0 (invalid window size)

arr := []int{1, 2}
k := 5
// Expected: 0 (window size greater than array length)

Similar Problem

Please visit https: https://codeandalgo.com for more such contents

Leave a Reply

Your email address will not be published. Required fields are marked *