Skip to content

Commit 5f5dd98

Browse files
Add SlidingWindowExample class for max sum subarray
1 parent 48ba1ae commit 5f5dd98

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
public class SlidingWindowExample {
2+
public static int maxSumSubarray(int[] arr, int k) {
3+
int maxSum = 0;
4+
int windowSum = 0;
5+
6+
// Compute sum of first window
7+
for (int i = 0; i < k; i++) {
8+
windowSum += arr[i];
9+
}
10+
maxSum = windowSum;
11+
12+
// Slide the window
13+
for (int i = k; i < arr.length; i++) {
14+
windowSum += arr[i] - arr[i - k]; // Add next element, remove first of the previous window
15+
maxSum = Math.max(maxSum, windowSum);
16+
}
17+
18+
return maxSum;
19+
}
20+
21+
public static void main(String[] args) {
22+
int[] arr = {2, 1, 5, 1, 3, 2};
23+
int k = 3;
24+
System.out.println("Maximum sum of subarray of size " + k + " is: " + maxSumSubarray(arr, k));
25+
}
26+
}

0 commit comments

Comments
 (0)