Maximum Sum Subarray of Size K
This program finds maximum sum subarray of size K using sliding window.
Problem Statement
Write a Java program to find maximum sum subarray of size 3.
Source Code
| 1 | public class MaxSumSubarrayK { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Max Sum Subarray of Size K"); |
| 4 | int[] arr = {2,1,5,1,3,2}; |
| 5 | int k=3, sum=0; |
| 6 | for(int i=0;i<k;i++) sum+=arr[i]; |
| 7 | int maxSum=sum; |
| 8 | for(int i=k;i<arr.length;i++){ |
| 9 | sum+=arr[i]-arr[i-k]; |
| 10 | maxSum=Math.max(maxSum,sum); |
| 11 | } |
| 12 | System.out.println("Maximum sum subarray of size "+k+" = "+maxSum); |
| 13 | } |
| 14 | } |
Program Output
Eduinq Max Sum Subarray of Size K Maximum sum subarray of size 3 = 9
Explanation
The sliding window maintains the sum of the current window of size k, and as the window slides forward it adds the new element and removes the oldest one, updating the maximum sum each step, demonstrating efficient fixed-size subarray sum calculation.