Skip to content

Commit 7174f73

Browse files
committed
finds maximum sum of subarray of window size K, in O(N^2) Time, O(1) space
1 parent 535d799 commit 7174f73

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package SlidingWindow;
2+
3+
public class MaximumSubarraySum {
4+
5+
// brute force approch - O(N^2) Time | O(1) Space
6+
public static int maxSubarraySum(int[] arr, int k) {
7+
8+
int maxsum = Integer.MIN_VALUE;
9+
10+
for (int i = 0; i <= arr.length - k; i++) {
11+
int currsum = 0;
12+
13+
for (int window = 0; window < k; window++) {
14+
currsum += arr[i + window];
15+
}
16+
maxsum = Math.max(maxsum, currsum);
17+
}
18+
19+
return maxsum;
20+
}
21+
22+
public static void main(String[] args) {
23+
int[] arr = { 1, 4, 2, 10, 23, 3, 1, 0, 20 };
24+
int windowSize = 4;
25+
System.out.println(maxSubarraySum(arr, windowSize));
26+
}
27+
}

0 commit comments

Comments
 (0)