Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Maximum Subarray problem in C++ #17

Merged
merged 1 commit into from Oct 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
75 changes: 75 additions & 0 deletions C++/Maximum_Subarray.cpp
@@ -0,0 +1,75 @@
#include<bits/stdc++.h>
typedef long long ll;

#define mod 1000000007
#define inf 1e9
#define rep(i,n) for(int i=0;i<n;i++)
#define w(t) ll tt;cin>>tt;while(tt--)
#define pb push_back
#define endl "\n"
#define vll vector<ll>
#define pi pair<ll,ll>
#define all(arr) arr.begin(),arr.end()
using namespace std;
void init_code(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
}


void solve(){
int n; cin>>n;
vector<int> a(n);
for(int i=0;i<n;i++) cin>>a[i];

int m; cin>>m;
vector<int> b(m);
for(int i=0;i<m;i++) cin>>b[i];

vector<int> tempa= a;
for(int i=0;i<m;i++){
if(b[i]>0){
a.push_back(b[i]);
tempa.insert(tempa.begin(),b[i]);
}
}

long long sum=0, maxsum=INT_MIN;
for(int i=0;i<a.size();i++){

sum+=a[i];
maxsum=max(maxsum,sum);
if(sum<0){
sum=0;
}
}
sum=0;
long long maxi=INT_MIN;
for(int i=0;i<tempa.size();i++){
sum+=tempa[i];
maxi=max(maxi,sum);
if(sum<0){
sum=0;
}
}


cout<<max(maxi,maxsum)<<endl;


}

int main(){
init_code();
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll t;cin>>t;

while(t--){
solve();
}

}
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -33,6 +33,8 @@
|21. | [Save Water Save Life](https://github.com/Sahiljawale/CodeChef/blob/main/C%2B%2B/Save_water_save_life.cpp) |
|22. | [The Old Saint And Three Questions](https://github.com/Sahiljawale/CodeChef/blob/main/C%2B%2B/The_old_saint_and_three_questions.cpp) |
|23. | [Vaccine Dates](https://github.com/Sahiljawale/CodeChef/blob/main/C%2B%2B/Vaccine_dates.cpp) |
|24. | [Maximum Subarray](https://github.com/Sahiljawale/CodeChef/blob/main/C%2B%2B/Maximum_Subarray.cpp) |


<br>

Expand Down