forked from Masked-coder11/gfg-POTD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02.01.2024.cpp
58 lines (47 loc) · 1.24 KB
/
02.01.2024.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
class Solution{
public:
long long int maxSumWithK(long long int a[], long long int n, long long int k)
{
if(k==1){
//kadane's algorithm
long long int sum=0;
long long int maxi=a[0];
for(long long int i=0; i<n;i++){
sum+=a[i];
maxi=max(sum,maxi);
if(sum<0) sum=0;
}
return maxi;
}
vector<long long int>v(n,0);
long long int sum=0;
v[0]=0;
for(long long int i=0; i<n;i++){
if(sum >=0){
sum+=a[i];
}
else{
sum=a[i];
}
if(sum<0){
sum=0;
}
v[i]=sum;
}
sum=0;
for(long long int i=0;i<=k-1;i++){
sum+=a[i];
}
long long int ans=sum;
long long int curr=sum-a[0]+a[k];
long long int i=1, j=k;
while(j<n){
ans = max(ans, curr + v[i-1]);
curr = curr - a[i];
i++;
j++;
curr = curr + a[j];
}
return ans;
}
};