#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define vll vector <ll>
#define for0(i,l,r) for(ll i = l;i<r;i++)
int main()
{
fastio;
ll n;
cin>>n;
vll a(n);
for0(i,0,n) cin>>a[i];
vll pre(n,0);
pre[0] = a[0];
for0(i,1,n){
pre[i] = pre[i-1]+a[i];
}
map<ll,ll> mp;
ll maxi = 0;
vll suffZero(n+1,0);
for(ll i=n-1;i>=0;i--){
if(pre[i]==0){
suffZero[i] = suffZero[i+1]+1;
}else suffZero[i] = suffZero[i+1];
}
ll maxFreq = INT_MAX;
for(ll i=n-1;i>=0;i--){
mp[pre[i]]++;
if(maxFreq==INT_MAX){
maxFreq = pre[i];
}else{
if(mp[pre[i]]>mp[maxFreq]){
maxFreq = pre[i];
}
}
if(a[i]==0 && pre[i]!=0){
maxi = max(maxi, max(suffZero[i],mp[maxFreq]));
}else if(a[i]==0 && pre[i]==0){
maxi = max(maxi,max(maxi+1,max(suffZero[i],mp[maxFreq])));
}else if(a[i]!=0 && pre[i]==0){
maxi++;
}
}
cout<<maxi;
}
// Online C++ compiler to run C++ program online
#include <bits/stdc++.h>
#include<map>
using namespace std;
int main() {
// Write C++ code here
int n;cin>>n;
vector<int>value(n);
int zero=-1,finalcount=0,prefixsum=0;
for(int i=0;i<n;i++){
cin>>value[i];
if(zero==-1){
if(value[i]==0){
zero=i;
}
else {
prefixsum+=value[i];
if(prefixsum==0)finalcount++;
}
}
}
for(int i=zero;i<n;i++){
map<int,int>count;
pair<int,int>maxi;
maxi.first=prefixsum;
maxi.second=1;
while(value[i]||i==zero){
prefixsum+=value[i];
count[prefixsum]++;
if(count[prefixsum]>maxi.second){
maxi.first=prefixsum;
maxi.second=count[prefixsum];
}
i++;
}
zero=i;
prefixsum=prefixsum-maxi.first;
finalcount+=maxi.second;
i=i-1;
}
std::cout << finalcount;
return 0;
}
The Given Code doesnot work in all cases.
ex: 3 0 6 -5 5
output :1 (3 -3 6 -5 5)
Expected : 2 (3 -9 6 -5 5)