dimanche 23 juillet 2017

how does recursion works if the the function have a loop and the recursion calls under it?

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int f,c[109],n,a,b,sum;
int flipping(int a,int b)
{
int ret1=0;
int ret2=0;
if(a<0 || a==n || b<0 || b==n)  return 0;
for(int i=a; i<=b; i++)
{
    if(c[i]==1)
        sum--;
    if(c[i]==0)
        sum++;
    f=sum;

}
ret1=max(f,flipping(a+1,b));
ret2=max(f,flipping(a,b-1));

return max(ret1,ret2);
}
int main()
{
cin >> n;
for(int i=0; i<n; i++)
{
    cin >> c[i];
    if(c[i]==1) sum++;
}
cout <<  flipping(0,n-1);

return 0;
}

this code is to find a range which if u flip all the values in it(from one to zero and from zero to one) .. u will have the max number of ones ... ex: 1 0 0 1 we pick the range (2,3) and have 4 ones

Aucun commentaire:

Enregistrer un commentaire