-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaximumSum.java
46 lines (39 loc) · 1.05 KB
/
MaximumSum.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
38
39
40
41
42
43
44
45
46
package collectionz;
//JAVA Code for Find maximum (or minimum)
//sum of a subarray of size k
import java.util.*;
class MaximumSum {
// Returns maximum sum in a subarray of size k.
public static int maxSum(int arr[], int n, int k)
{
// k must be greater
if (n < k)
{
System.out.println("Invalid");
return -1;
}
// Compute sum of first window of size k
int res = 0;
for (int i=0; i<k; i++)
res += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
int curr_sum = res;
for (int i=k; i<n; i++)
{
curr_sum += arr[i] - arr[i-k];
res = Math.max(res, curr_sum);
}
return res;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20};
int k = 4;
int n = arr.length;
System.out.println(maxSum(arr, n, k));
}
}