Skip to content

Commit 02d0c0e

Browse files
committed
Added Sliding Window: Maximum Sum Subarray of Size K
1 parent 68746f8 commit 02d0c0e

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
*
1616
* @param <T> The type of elements to be stored in the Bloom filter.
1717
*/
18-
@SuppressWarnings("rawtypes")
18+
1919
public class BloomFilter<T> {
2020

2121
private final int numberOfHashFunctions;
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.thealgorithms.slidingwindow;
2+
3+
/**
4+
* Problem: Find the maximum sum of any contiguous subarray of size K
5+
* Approach: Sliding Window
6+
* Time Complexity: O(n)
7+
* Space Complexity: O(1)
8+
*/
9+
public class MaximumSumSubarrayOfSizeK {
10+
11+
/**
12+
* Returns the maximum sum of any contiguous subarray of size k.
13+
*
14+
* @param arr input array
15+
* @param k window size
16+
* @return maximum sum of subarray of size k
17+
* @throws IllegalArgumentException if k <= 0 or arr length < k
18+
*/
19+
public static int maxSumSubarray(int[] arr, int k) {
20+
if (arr == null || arr.length < k || k <= 0) {
21+
throw new IllegalArgumentException("Invalid input");
22+
}
23+
24+
int windowSum = 0;
25+
for (int i = 0; i < k; i++) {
26+
windowSum += arr[i];
27+
}
28+
29+
int maxSum = windowSum;
30+
31+
for (int end = k; end < arr.length; end++) {
32+
windowSum += arr[end] - arr[end - k];
33+
maxSum = Math.max(maxSum, windowSum);
34+
}
35+
36+
return maxSum;
37+
}
38+
39+
// Example test
40+
public static void main(String[] args) {
41+
int[] arr = {2, 1, 5, 1, 3, 2};
42+
int k = 3;
43+
System.out.println("Max sum of subarray of size " + k + " = " + maxSumSubarray(arr, k));
44+
}
45+
}

0 commit comments

Comments
 (0)