Codeforces 327A. Flipping Game Solution
Algorithm
1. Consider all subarrays and find a subarray with maximum value of (count of 1s) – (count of 0s)
2. Considers this value be maxDiff. Finally return count of zeros in original array + maxDiff.
Solution in C++:
///La ilaha illellahu muhammadur rasulullah
///******Bismillahir-Rahmanir-Rahim******///
///AH Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
-
- int n,a[109],i,j,zero=0,one=0,one1=0,mxcnt=0;
- cin>>n;
- for(i=0; i<n; i++)
- {
- cin>>a[i];
- if(a[i]==1)
- one1++;
- }
- if(n==1&&a[0]==1)
- {
- cout<<"0"<<endl;
- return 0;
- }
- else if(one1==n)
- {
- cout<<n-1<<endl;
- return 0;
- }
- for(i=0; i<n; i++)
- {
- zero=0;
- one=0;
- for(j=i; j<n; j++)
- {
- (a[j]==0)?zero++:one++;
- mxcnt=max(mxcnt,zero-one);
- }
- }
- cout<<one1+mxcnt<<endl;
- }
No comments