Why am I getting WA in the question LEPERMUT?

I am using the logic that for global inversions to be greater than local inversions, there must be atleast one pair (i,j), such that i < (j-1) and a[i]>a[j]. Is there any corner case for which this logic is wrong? If not, what is wrong with the following implementation?

The question is at the following link: https://www.codechef.com/problems/LEPERMUT

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<set>
#include<vector>
#include<utility>

using namespace std;

int main( ) {

    int t, n, maxSoFar, maxIndex, tmp;
    bool flag;
    cin>>t;

    while ( t--  ) {
        cin>>n;
        flag = false;
        for ( int i = 0; i < n; i++ ) {
            cin>>tmp;
            if ( flag == true ) {
                continue;
            }

            if ( i == 0 ) {
                maxSoFar = tmp;
                maxIndex = 0;
            }
            else  {
                if ( maxSoFar > tmp ) {
                    if ( ( i - maxIndex) > 1 ) {
                        flag = true;
                    }
                }
                else if ( maxSoFar < tmp ) {
                    maxSoFar = tmp;
                    maxIndex = i;
                }
            }
        }
        if ( flag == true ) {
            cout<<"NO"<<endl;
        }
        else {
            cout<<"YES"<<endl;
        }
    }

    return 0;
}         cout<<"NO"<<endl;
        }
        else {
            cout<<"YES"<<endl;
        }
    }

    return 0;
}

Your logic is wrong man. Consider the test input
3 5 2