Optimising the solution

THe following code is the solution of the PROBLEM : VALIDSTK ( VALID STACK OPERATIONS ) :

QUES: The solution is correct but it is showing TIME LIMIT EXCEEDED. Can anyone help me in optimising the given code ???


int main()

{

int t;

std::cin >> t;

while(t--)

{

 int n;

 std::cin >> n;

 int a[n];

 for(int i=0;i<n;i++)

 {

   std::cin >> a[i];

 }

   if(a[0]==0)

    {

      std::cout << "Invalid" << '\n';

   //   break;

    }

    else

  {

    int c=0;

     for(int i=1;i<=n;i++)

    {

      if(count(a,a+i,0)>count(a,a+i,1))

       {

        std::cout << "Invalid" << '\n';

        break;

       }

      else

       c=c+1;

    }

    if(c==n)

    std::cout << "Valid" << '\n';

   }

  }

   return 0;

 }

The complexity of count function is linear which is resulting total complexity T*N^2. You need to optimize that.
http://www.cplusplus.com/reference/algorithm/count/

You can optimize by maintaining two variables counting zero and one and checking if at any instant

number of zero > number of one

https://www.codechef.com/viewsolution/22083712