Last active
May 27, 2018 17:07
-
-
Save mishal23/6f9c441f5a781c4207c9f016db1423bb to your computer and use it in GitHub Desktop.
Find subarray containing atleast k numbers with maximum sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "bits/stdc++.h" | |
using namespace std; | |
int main() | |
{ | |
int n,i,k; | |
cin>>n; | |
vector<int> v; | |
for(i=0;i<n;i++) | |
{ | |
int x; | |
cin>>x; | |
v.push_back(x); | |
} | |
cin>>k; | |
int maxSum[n]; | |
maxSum[0] = v[0]; | |
int max_here = v[0]; | |
for(i=1;i<n;i++) | |
{ | |
max_here = max(v[i],max_here+v[i]); | |
maxSum[i] = max_here; | |
} | |
int sum=0; | |
if(k>n) | |
{ | |
cout<<"Not possible"<<endl; | |
} | |
else | |
{ | |
if(k>0) | |
{ | |
for(i=0;i<k;i++) | |
{ | |
sum+=v[i]; | |
} | |
int max_sum = sum; | |
for(i=k;i<n;i++) | |
{ | |
sum+=v[i]-v[i-k]; | |
max_sum = max(max_sum, sum); | |
max_sum = max(max_sum,sum+maxSum[i-k]); | |
} | |
cout<<max_sum<<endl; | |
} | |
else if(k<=0) | |
{ | |
int max_sum=INT_MIN; | |
for(i=0;i<n;i++) | |
{ | |
if(max_sum<maxSum[i]) | |
{ | |
max_sum = maxSum[i]; | |
} | |
} | |
if(max_sum<0) | |
{ | |
max_sum=0; | |
} | |
cout<<max_sum<<endl; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment