-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathmax_subarray_sum_with_length_k.java
37 lines (31 loc) · 1.34 KB
/
max_subarray_sum_with_length_k.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package SlidingWindow;
public class MaxSubarraySumWithLengthK {
public static void main(String[] args) {
final long startTime = System.currentTimeMillis();
final long beforeUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
int[] array = {-3, 4, -2, 5, 3, -2, 8, 2, -1, 4};
int targetLength = 5;
int ans = solve(array, targetLength);
System.out.println(ans);
final long endTime = System.currentTimeMillis();
final long afterUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
final long actualMemUsed = afterUsedMem-beforeUsedMem;
System.out.println("Runtime " + (endTime - startTime) + " ms");
System.out.println("Space " + actualMemUsed + " B");
}
public static int solve(int[] array, int targetLength) {
// O(n) time | O(1) space
int maxSubarraySum = 0;
int currentSum = 0;
int length = array.length;
for (int i = 0; i < targetLength; i++)
currentSum += array[i];
int startIdx = 1;
int endIdx = targetLength;
while (endIdx < length) {
currentSum = currentSum + array[endIdx++] - array[startIdx++ - 1];
maxSubarraySum = Math.max (maxSubarraySum, currentSum);
}
return maxSubarraySum;
}
}