Max Sum Subarray of Size K

01 Min
🔄
Course In Progress In Progress

This article belongs to the DSA for Interviews course, which is actively in development with new lessons rolling out regularly.

Table of Contents 2 sections

Problem Overview

Solution

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		int[] nums = new int[]{1,4,3,10,23,3,1,0,20};
		int k=4;
		
		int n=nums.length;
		int windowStart=0, sum=0, maxSum=0;
		
		for(int windowEnd = 0; windowEnd<n; windowEnd++){
		    sum+=nums[windowEnd];
		    if((windowEnd-windowStart+1) == k ){
		        maxSum = Math.max(maxSum, sum);
		        sum-=nums[windowStart];
		        windowStart+=1;
		    }
		}
		
		System.out.println(maxSum);
	}
}

Maximum Sum Subarray of Size K

Find the maximum sum of any contiguous subarray of size K using the sliding window technique.

Initialize Sliding Window

windowStart: 0
windowEnd: -1
sum: 0
maxSum: 0
k: 4

We need to find the maximum sum of a contiguous subarray of size 4. Initialize windowStart, sum, and maxSum to 0.

$ int windowStart = 0, sum = 0, maxSum = 0;
windowStart
1
[0]
4
[1]
3
[2]
10
[3]
23
[4]
3
[5]
1
[6]
0
[7]
20
[8]
Step 1 of 35
Speed