Maximum Sum Subarray of Size K - Java Solution

1. Introduction

In this blog post, we'll explore a common problem in array processing - finding the maximum sum of a contiguous subarray of a fixed size. This problem is a variant of the sliding window technique, which is often used for array and string manipulation.

Problem

Given an array of positive integers and a positive number k, find the maximum sum of any contiguous subarray of size k.

2. Solution Steps

1. Use a sliding window of size k.

2. Slide the window across the array while keeping track of the sum of elements in the current window.

3. Update the maximum sum found so far.

4. Return the maximum sum after traversing the entire array.

3. Code Program

public class Solution {

    // Main method for testing
    public static void main(String[] args) {
        int[] arr1 = {3, 5, 2, 1, 7};
        System.out.println("Maximum sum of subarray of size 2: " + findMaxSumSubarray(arr1, 2));

        int[] arr2 = {4, 2, 3, 5, 1, 2};
        System.out.println("Maximum sum of subarray of size 3: " + findMaxSumSubarray(arr2, 3));
    }

    // Method to find the maximum sum of a subarray of size k
    public static int findMaxSumSubarray(int[] arr, int k) {
        int maxSum = 0, windowSum = 0;
        int start = 0;

        for (int end = 0; end < arr.length; end++) {
            windowSum += arr[end]; // Add the next element into the window

            // Slide the window when we hit the size k
            if (end >= k - 1) {
                maxSum = Math.max(maxSum, windowSum); // Update the maximum sum
                windowSum -= arr[start]; // Remove the element going out of the window
                start++; // Slide the window ahead
            }
        }
        return maxSum;
    }
}

Output:

Maximum sum of subarray of size 2: 8
Maximum sum of subarray of size 3: 10

Explanation:

The findMaxSumSubarray method implements the sliding window technique to find the subarray of size k with the maximum sum. 

For example, for the input array [3, 5, 2, 1, 7] and k=2, it calculates the maximum sum as 8 from the subarray [1, 7]. 

Similarly, for the input [4, 2, 3, 5, 1, 2] and k=3, the maximum sum is 10 from the subarray [2, 3, 5].

Comments