-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMaximumSumSubarrayOfSizeK.java
44 lines (44 loc) · 1.13 KB
/
MaximumSumSubarrayOfSizeK.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
/*https://practice.geeksforgeeks.org/problems/max-sum-subarray-of-size-k5313/1*/
/*Prateekshya's Solution*/
class Solution{
static int maximumSumSubarray(int K, ArrayList<Integer> Arr,int N){
int currSum = 0, maxSum = 0;
for (int i = 0; i < K; ++i)
currSum += Arr.get(i);
if (currSum > maxSum)
maxSum = currSum;
for (int i = K; i < N; ++i)
{
currSum -= Arr.get(i-K);
currSum += Arr.get(i);
if (currSum > maxSum)
maxSum = currSum;
}
return maxSum;
}
}
/*Pratik's Solution*/
class Solution{
static int maximumSumSubarray(int K, ArrayList<Integer> Arr,int N)
{
int max = Integer.MIN_VALUE;
// code here
int cur = 0;
for(int i = 0;i < K;i++)
{
cur+=Arr.get(i);
}
if(max<cur)max = cur;
cur-=Arr.get(0);
int left = 1,right = K;
while(right<N)
{
cur+=Arr.get(right);
if(cur>max)max=cur;
cur-=Arr.get(left);
left++;
right++;
}
return max;
}
}