function ProblemSolver() {
    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;
    this.CLEAR_ARRAY_PER_CASE = false;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , prev ;
        res = ( 1 << 20 ) ;
        prev = -1 ;
        fl = 1 ;
        for( i = 0 ; i < this.n ; i++ ) {
        	if( this.arr[ i ] >= prev ) {
        		prev = this.arr[ i ] ;
        	}
        	else {
        		fl = 0 ;
        		prev = -1 ;
        		for( j = i ; j < this.n ; j++ ) {
        			if( this.arr[ j ] >= prev ) {
		        		prev = this.arr[ j ] ;
		        	}
		        	else {
		        		break ;
		        	}
        		}
        		if( j == this.n && this.arr[ this.n - 1 ] <= this.arr[ 0 ] ) {
        			res = this.n - i ;
        		}
        		break ;
        	}
        }
        if( fl == 1 ) {
        	res = 0 ;
        }
        if( res == ( 1 << 20 ) ) {
        	res = -1 ;
        }
        print( res );
    };

    this.init = function() {
        this.lim1 = 100010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.n = irObj.nextInt();
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr[ i ] = irObj.nextInt();
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

    this.clearArraysPerCase = function() {
        var i;
        this.arr = new Array();
        this.adj_list = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 );
            this.adj_list.push( new Array() );
        }
    };

    this.clearPerCase = function() {
        this.cn = 0;
        this.cc++;
        if( this.CLEAR_ARRAY_PER_CASE == true ) {
            this.clearArraysPerCase() ;
        }
    };

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adj_list = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( "" );
            this.vis.push( 0 );
            this.arr.push( 0 );
            this.brr.push( 0 );
            this.adj_list.push( new Array() );
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() );
            this.done.push( new Array() );
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 );
                this.done[ i ].push( 0 );
            }
        }
    };

    this.init();
}

function InputReader() {
    var self = this ;
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;
    this.callBackFunction = null ;
    this.parentContext = null ;

    this.readAllLines = function() {
        var singleLine;
        while( true ) {
            try {
                singleLine = readline();
                if( singleLine == null ) {
                    break;
                }
            }
            catch( ex ) {
                break;
            }
            this.allLines.push( singleLine );
        }
    };

    this.readAllLinesFromRhino = function() {
        var brObj , line ;
        importPackage( java.io ) ;
        importPackage( java.lang ) ;
        brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;
        this.allLines = [] ;
        while( true ) {
            line = brObj.readLine() ;
            if( line == null ) {
                break;
            }
            this.allLines.push( line ) ;
        }
    };

    this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {
        self.chunkData += chunk ;
    };

    this.readEndFromNodeJsJudgeServer = function() {
        self.parseRawData( self.chunkData ) ;
        self.parentContext.runCases() ;
    };

    this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {
        this.parentContext = parentContext ;
        process.stdin.resume() ;
        process.stdin.setEncoding( 'utf8' ) ;
        this.chunkData = '' ;
        process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;
        process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        this.allLines = [] ;
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString );
                currentString = "";
            }
            else {
                currentString += data[ i ];
            }
        }
        if( currentString != "" ) {
            this.allLines.push( currentString );
        }
    };

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx;
        if( flag == 0 ) {
            if( this.currrentCharacterIndex != 0 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            res = "";
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
            }
            this.currrentLineNumber++;
            this.currrentCharacterIndex = 0;
            return res;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( "No more tokens available!" );
            }
            startIdx = -1;
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {
                    startIdx = i;
                    break;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
                continue;
            }
            res = "";
            endIdx = len - 1 ;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {
                    res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;
                }
                else {
                    res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );
                }
            }
            this.currrentCharacterIndex = endIdx;
            if( endIdx == len - 1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            return res;
        }
    };

    this.nextInt = function() {
        return parseInt( this.next( 1 ) );
    };

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) );
    };

    this.nextString = function() {
        return this.next( 1 );
    };

    this.nextLine = function() {
        return this.next( 0 );
    };
}

function FileOutputHandler() {
    this.resultantStringArray = new Array();

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString );
    };

    this.clearPercase = function() {
        this.resultantStringArray = new Array();
    };

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath;
        res = "";
        sz = this.resultantStringArray.length;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += "\n";
            }
            res += this.resultantStringArray[ i ];
        }
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

function CodeExecutioner() {
    this.irObj = new InputReader();
    this.psObj = new ProblemSolver();
    this.fohObj = new FileOutputHandler();

    this.runCases = function() {
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt();
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase();
                this.psObj.getInput( this.irObj );
                this.psObj.solveCase();
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase();
                hasMoreTestCases = this.psObj.getInput( this.irObj );
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase();
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );
        }
    };

    this.detectEnvironmentType = function() {
        var environmentType = null ;
        try {
            if( importPackage != null ) {
                environmentType = 'rhino' ;
            }
        }
        catch( ex1 ) {
            try {
                //for nodejs local server check
                if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {
                    environmentType = 'local-node-js' ;
                }
            }
            catch( ex2 ) {
                try {
                    if( readline == null || typeof( readline ) != 'function' ) {
                        environmentType = 'server-node-js' ;
                    }
                    else {
                        try {
                            if( Map != null ) {
                                environmentType = 'spider-monkey' ;
                            }
                            else {
                                environmentType = 'javascript-v8' ;
                            }
                        }
                        catch( ex3 ) {
                            environmentType = 'javascript-v8' ;
                        }
                    }
                }
                catch( ex3 ) {
                    environmentType = 'server-node-js' ;
                }
            }
        }
        return environmentType ;
    };

    this.configureStreamsAndReadInput = function() {
        var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;
        isNodeJsJudgeServer = false ;
        environmentType = this.detectEnvironmentType() ;
        if( environmentType == 'local-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments );
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );
            this.runCases() ;
        }
        else if( environmentType == 'server-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;
        }
        else if( environmentType == 'javascript-v8' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
        else if( environmentType == 'rhino' ) {
            this.irObj.readAllLinesFromRhino();
            this.runCases() ;
        }
        else if( environmentType == 'spider-monkey' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
    };

    this.configureStreamsAndReadInput();
}

new CodeExecutioner();

//

var line = readline();

var ray = readline().split(' ');
var n = parseInt(line);
var bRay = [];

for(var i = 0 ; i < n ; i++) {
	bRay.push(parseInt(ray[i]));
}

print(foo(n,bRay));

//console.log(foo(2,[1,2]));

//checker(3,[1,3,2],0);
function foo(n,ray) {
	var count = 0;
	//console.log(checker(n,bRay,1));

	for(var i = 0 ; i < n-1;i++) {
		if (ray[i] > ray[i+1]) {

			for(var j = 1 ; j < n ; j++) {
				//.log((j+i)%n,i);
				if ( ray[(j+i) % n]  > ray[(j+i+1) %n]) {
					return -1;
				}

			}
			return n-(i+1);

		}

	}

	return 0;
}

/*
function checker(n,ray,p) {
//	var s = "";
//	var d = "";
	for(var i = 0 ; i < n-1 ; i++) {

		if ( ray[(i+p) %n] > ray[(i+1+p) %n]) {
			return false;
		}

	}

	return true;
}*/

var n=parseInt(readline());
var ar=readline().split(" ");
for(var i=0;i<n;i++){ar[i]=parseInt(ar[i]);}

var res=0;

if(ar[n-1]>ar[0])
{
   for(var i=0;i<n-1;i++){
           if(ar[i]>ar[i+1]){res=-1;break;}
                        }
}

else{res++;
for(var i=n-1;i>0;i--){

               if(ar[i]>=ar[i-1]){res++;}
else{
for(var y=0;y<i-1;y++){
         if(ar[y]>ar[y+1]){res=-1;break;}
}break;

}
}if(res===n){res=0;}
}print(res);

var l = readline()|0,
    arr = readline().split(' ').map(Number),
    inf = 0,
    steps = 0;

    if (arr[l-1]>arr[0]) {
        inf +=1;
    }
for (var i=0; i<l-1; i++) {
    if (arr[i] > arr[i+1]) {
        inf +=1;
        steps = l-1 - i;
    }
}
if (inf == 0) {
    print('0');
} else if (inf == 1){
    print(steps);
} else {
    print('-1');
}

;(function () {

    print(function () {
        var n = +readline(),
            a = readline().split(' ').map(Number),
            d = 0, r = null;

        if (n === 2) {
            return a[0] <= a[1] ? 0 : 1;
        }

        a = a.concat([a[0]]);

        a.forEach(function (e, i, a) {
            if (i === 0) return;
            if (e < a[i - 1]) {
                d++;
                r = i;
            }
        });

        if (d === 0) return 0;
        if (d > 1) return -1;
        return n - r;
    }.call(this));

}.call(this));

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline()),
		values = tokenizeIntegers(readline());
	for (var seek = 1; seek < n; ++seek) {
		if (values[seek-1] > values[seek]) {
			break;
		}
	}
	if (seek == n) {
		return 0;
	}
	var end = seek-1;
	for (var i = end+2; i < n; ++i) {
		if (values[i-1] > values[i]) {
			return -1;
		}
	}
	if (values[n-1] > values[0]) {
		return -1;
	}
	return n-end-1;
}

print(main());

var n = +readline();
var s = readline().split(' ').map(Number);
var ind = -1;
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		ind = i+1;
		s = s.slice(ind).concat(s.slice(0, ind));
		break;
	}
}
if (ind == -1) print(0);
else {
	for (var i=0; i<n-1; i++) {
		if (s[i]>s[i+1]) {
		print(-1);
		ind = -1;
		break;
		}
	}
	if (ind != -1) print(n-ind);
}

//

var line = readline();

var ray = readline().split(' ');
var n = parseInt(line);
var bRay = [];

for(var i = 0 ; i < n ; i++) {
	bRay.push(parseInt(ray[i]));
}

print(foo(n,bRay));

//console.log(foo(4,[3,4,1,2]));

//checker(3,[1,3,2],0);
function foo(n,ray) {
	var count = 0;
	//console.log(checker(n,bRay,1));

	for(var i = 0 ; i < n-1;i++) {
		if (ray[i] > ray[i+1]) {

			for(var j = 1 ; j < n ; j++) {
				//.log((j+i)%n,i);
				if ( ray[(j+i) % n]  > ray[(j+i+1) %n]) {
					return -1;
				}

			}
			return i+1;

		}

	}

	return 0;
}

/*
function checker(n,ray,p) {
//	var s = "";
//	var d = "";
	for(var i = 0 ; i < n-1 ; i++) {

		if ( ray[(i+p) %n] > ray[(i+1+p) %n]) {
			return false;
		}

	}

	return true;
}*/

//

var line = readline();

var ray = readline().split(' ');
var n = parseInt(line);
var bRay = [];

for(var i = 0 ; i < n ; i++) {
	bRay.push(parseInt(ray[i]));
}

print(foo(n,bRay));

//console.log(foo(3,[1,3,2]));
function foo(n,bRay) {
	var count = 0;
	//console.log(checker(n,bRay,1));

		for(var i = 0 ; i < n ; i++) {

			if ( checker(n,bRay,i)) {
				//console.log(checker(n,bRay,i),n,bRay,i);
				return count;
			}
			count++;

		}

	return -1;

}

function checker(n,ray,p) {
	//console.log(n,ray,p);
	for(var i = 0 ; i < n ; i++) {

		var j = (i+p) %n ;
		//console.log(ray[j]);
		if ( ray[j] > ray[(j+1)%n]) {
			return false;
		}

	}
	//console.log("e");
	return true ;

}

function ProblemSolver() {
    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;
    this.CLEAR_ARRAY_PER_CASE = false;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , prev ;
        res = ( 1 << 20 ) ;
        prev = -1 ;
        fl = 1 ;
        for( i = 0 ; i < this.n ; i++ ) {
        	if( this.arr[ i ] >= prev ) {
        		prev = this.arr[ i ] ;
        	}
        	else {
        		fl = 0 ;
        		prev = -1 ;
        		for( j = i ; j < this.n ; j++ ) {
        			if( this.arr[ i ] >= prev ) {
		        		prev = this.arr[ i ] ;
		        	}
		        	else {
		        		break ;
		        	}
        		}
        		if( j == this.n && this.arr[ this.n - 1 ] <= this.arr[ 0 ] ) {
        			res = this.n - i ;
        		}
        		break ;
        	}
        }
        if( fl == 1 ) {
        	res = 0 ;
        }
        if( res == ( 1 << 20 ) ) {
        	res = -1 ;
        }
        print( res );
    };

    this.init = function() {
        this.lim1 = 100010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.n = irObj.nextInt();
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr[ i ] = irObj.nextInt();
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

    this.clearArraysPerCase = function() {
        var i;
        this.arr = new Array();
        this.adj_list = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 );
            this.adj_list.push( new Array() );
        }
    };

    this.clearPerCase = function() {
        this.cn = 0;
        this.cc++;
        if( this.CLEAR_ARRAY_PER_CASE == true ) {
            this.clearArraysPerCase() ;
        }
    };

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adj_list = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( "" );
            this.vis.push( 0 );
            this.arr.push( 0 );
            this.brr.push( 0 );
            this.adj_list.push( new Array() );
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() );
            this.done.push( new Array() );
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 );
                this.done[ i ].push( 0 );
            }
        }
    };

    this.init();
}

function InputReader() {
    var self = this ;
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;
    this.callBackFunction = null ;
    this.parentContext = null ;

    this.readAllLines = function() {
        var singleLine;
        while( true ) {
            try {
                singleLine = readline();
                if( singleLine == null ) {
                    break;
                }
            }
            catch( ex ) {
                break;
            }
            this.allLines.push( singleLine );
        }
    };

    this.readAllLinesFromRhino = function() {
        var brObj , line ;
        importPackage( java.io ) ;
        importPackage( java.lang ) ;
        brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;
        this.allLines = [] ;
        while( true ) {
            line = brObj.readLine() ;
            if( line == null ) {
                break;
            }
            this.allLines.push( line ) ;
        }
    };

    this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {
        self.chunkData += chunk ;
    };

    this.readEndFromNodeJsJudgeServer = function() {
        self.parseRawData( self.chunkData ) ;
        self.parentContext.runCases() ;
    };

    this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {
        this.parentContext = parentContext ;
        process.stdin.resume() ;
        process.stdin.setEncoding( 'utf8' ) ;
        this.chunkData = '' ;
        process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;
        process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        this.allLines = [] ;
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString );
                currentString = "";
            }
            else {
                currentString += data[ i ];
            }
        }
        if( currentString != "" ) {
            this.allLines.push( currentString );
        }
    };

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx;
        if( flag == 0 ) {
            if( this.currrentCharacterIndex != 0 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            res = "";
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
            }
            this.currrentLineNumber++;
            this.currrentCharacterIndex = 0;
            return res;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( "No more tokens available!" );
            }
            startIdx = -1;
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {
                    startIdx = i;
                    break;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
                continue;
            }
            res = "";
            endIdx = len - 1 ;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {
                    res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;
                }
                else {
                    res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );
                }
            }
            this.currrentCharacterIndex = endIdx;
            if( endIdx == len - 1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            return res;
        }
    };

    this.nextInt = function() {
        return parseInt( this.next( 1 ) );
    };

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) );
    };

    this.nextString = function() {
        return this.next( 1 );
    };

    this.nextLine = function() {
        return this.next( 0 );
    };
}

function FileOutputHandler() {
    this.resultantStringArray = new Array();

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString );
    };

    this.clearPercase = function() {
        this.resultantStringArray = new Array();
    };

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath;
        res = "";
        sz = this.resultantStringArray.length;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += "\n";
            }
            res += this.resultantStringArray[ i ];
        }
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

function CodeExecutioner() {
    this.irObj = new InputReader();
    this.psObj = new ProblemSolver();
    this.fohObj = new FileOutputHandler();

    this.runCases = function() {
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt();
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase();
                this.psObj.getInput( this.irObj );
                this.psObj.solveCase();
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase();
                hasMoreTestCases = this.psObj.getInput( this.irObj );
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase();
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );
        }
    };

    this.detectEnvironmentType = function() {
        var environmentType = null ;
        try {
            if( importPackage != null ) {
                environmentType = 'rhino' ;
            }
        }
        catch( ex1 ) {
            try {
                //for nodejs local server check
                if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {
                    environmentType = 'local-node-js' ;
                }
            }
            catch( ex2 ) {
                try {
                    if( readline == null || typeof( readline ) != 'function' ) {
                        environmentType = 'server-node-js' ;
                    }
                    else {
                        try {
                            if( Map != null ) {
                                environmentType = 'spider-monkey' ;
                            }
                            else {
                                environmentType = 'javascript-v8' ;
                            }
                        }
                        catch( ex3 ) {
                            environmentType = 'javascript-v8' ;
                        }
                    }
                }
                catch( ex3 ) {
                    environmentType = 'server-node-js' ;
                }
            }
        }
        return environmentType ;
    };

    this.configureStreamsAndReadInput = function() {
        var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;
        isNodeJsJudgeServer = false ;
        environmentType = this.detectEnvironmentType() ;
        if( environmentType == 'local-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments );
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );
            this.runCases() ;
        }
        else if( environmentType == 'server-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;
        }
        else if( environmentType == 'javascript-v8' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
        else if( environmentType == 'rhino' ) {
            this.irObj.readAllLinesFromRhino();
            this.runCases() ;
        }
        else if( environmentType == 'spider-monkey' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
    };

    this.configureStreamsAndReadInput();
}

new CodeExecutioner();

var n = +readline();
var s = readline().split(' ').map(Number);
var min = 1000000;
var ind = 0;
var count = 0;
for (var i=0; i<n; i++) {
	if (s[i]<=min) {
		min = s[i];
		ind = i;
	}
}
s = s.slice(ind).concat(s.slice(0, ind));
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		print(-1);
		min = 10000000;
		break;
	}
	if (s[i]==s[i+1]) {
		count++;
	}
}
if (min != 10000000) {
	if (ind == 0 || count == n-1) print(0);
	else print(n-ind);
}

var n = +readline();
var s = readline().split(' ').map(Number);
var min = 1000000;
var ind = 0;
for (var i=0; i<n; i++) {
	if (s[i]<=min) {
		min = s[i];
		ind = i;
	}
}
s = s.slice(ind).concat(s.slice(0, ind));
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		print(-1);
		min = 10000000;
		break;
	}
}
if (min != 10000000) {
	if (ind == 0) print(0);
	else print(n-ind);
}

var n = +readline();
var s = readline().split(' ').map(Number);
var min = Math.min.apply(null, s);
var ind = s.indexOf(min);
var count = 0;
s = s.slice(ind).concat(s.slice(0, ind));
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		print(-1);
		min = 10000000;
		break;
	}
	if (s[i]==s[i+1]) {
		count++;
	}
}
if (min != 10000000) {
	if (ind == 0 || count == n-1) print(0);
	else print(n-ind);
}

var n = +readline();
var s = readline().split(' ').map(Number);
var min = 1000000;
var ind = 0;
for (var i=0; i<n; i++) {
	if (s[i]<=min) {
		min = s[i];
		ind = i;
	}
}
s = s.slice(ind).join('') + s.slice(0, ind).join('');
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		print(-1);
		min = 10000000;
		break;
	}
}
if (min != 10000000) {
	if (ind == 0) print(0);
	else print(n-ind);
}

var n = +readline();
var s = readline().split(' ').map(Number);
var min = 1000000;
var ind = 0;
for (var i=0; i<n; i++) {
	if (s[i]<=min) {
		min = s[i];
		ind = i;
	}
}
s = s.slice(ind).concat(s.slice(0, ind));
print(s);
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		print(-1);
		min = 10000000;
		break;
	}
}
if (min != 10000000) {
	if (ind == 0) print(0);
	else print(n-ind);
}

var n=parseInt(readline());
var ar=readline().split(" ");

var res=0;

if(parseInt(ar[n-1])>parseInt(ar[0]))
{
   for(var i=0;i<n-1;i++){
           if(parseInt(ar[i])>parseInt(ar[i+1])){res=-1;break;}
                        }
}

else{
res++;
for(var i=n-1;i>0;i--){

               if(parseInt(ar[i-1])<=parseInt(ar[i])){res++;}
else{
for(var y=i-1;y>0;y--){
         if(parseInt(ar[y])<parseInt(ar[y-1])){res=-1;break;}
}
}
break;
}
}print(res);

var n=parseInt(readline());
var ar=readline().split(" ");
var res=0;
if(parseInt(ar[n-1])>parseInt(ar[0])){
for(var i=0;i<n-1;i++){
if(parseInt(ar[i])>parseInt(ar[i+1])){res=-1;break;}
}
}
else{
res++;
for(var i=n-1;i>0;i--){

if(parseInt(ar[i-1])<parseInt(ar[i])){res++;}
else{
for(var y=i-1;y>0;y--){
if(parseInt(ar[y])<parseInt(ar[y-1])){res=-1;break;}
}
}
break;
}
}print(res);

var n=parseInt(readline());
var ar=readline().split(" ");
for(var i=0;i<n;i++){ar[i]=parseInt(ar[i]);}

var res=0;

if(ar[n-1]>ar[0])
{
   for(var i=0;i<n-1;i++){
           if(ar[i]>ar[i+1]){res=-1;break;}
                        }
}

else{res++;
for(var i=n-1;i>0;i--){

               if(ar[i]>ar[i-1]){res++;}
else{
for(var y=0;y<i-1;y++){
         if(ar[y]>ar[y+1]){res=-1;break;}
}break;

}
}
}print(res);

var l = readline()|0,
    arr = readline().split(' ').map(Number),
    chkr = false,
    chk = false;

while (chkr == false) {
    var res = 0;
    for (var i = 0; i < l-1; i++) {
        if (arr[i] > arr[i+1]) {
            arr.unshift(arr.pop(arr[l-1]));
            chkr = false;
            break;
        }
        chkr = true;
        chk = true;
        res += 1;
    }
    if (res >= l-1) {
        chkr = true;
        chk = false;
    }
}
if (chk == true) {
   print(res);
}
else {
   print ("-1");
}

;(function () {

    print(function () {
        var n = +readline(),
            a = readline().split(' ').map(Number),
            d = 0, r = null;

        if (n === 2) {
            return a[0] <= a[1] ? 0 : 1;
        }

        a.forEach(function (e, i, a) {
            if (i === 0) return;
            if (e < a[i - 1]) {
                d++;
                r = i;
            }
        });

        if (d === 0) return 0;
        if (d > 1) return -1;
        return n - r;
    }.call(this));

}.call(this));

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline()),
		values = tokenizeIntegers(readline());
	for (var seek = 1; seek < n; ++seek) {
		if (values[seek-1] > values[seek]) {
			break;
		}
	}
	if (seek == n) {
		return 0;
	}
	var end = seek-1;
	for (var i = end+2; i < n; ++i) {
		if (values[i-1] > values[i]) {
			return -1;
		}
	}
	if (values[n-1] > values[0]) {
		return -1;
	}
	return Math.min(end+1, n-end-1);
}

print(main());

//

var line = readline();

var ray = readline().split(' ');
var n = parseInt(line);
var bRay = [];

for(var i = 0 ; i < n ; i++) {
	bRay.push(parseInt(ray[i]));
}

print(foo(n,bRay));

//console.log(foo(2,[2,1]));
function foo(n,bRay) {
	var count = 0;
	//console.log(checker(n,bRay,1));
	if ( !checker(n,bRay,0) ) {

		for(var i = 1 ; i < n ; i++) {

			count++;
			if ( checker(n,bRay,i)) {
				return count;
			}

		}
	}

	else {
		return 0;
	}

	return -1;

}

function checker(n,ray,p) {
	for(var i = 0 ; i < n-1 ; i++) {
		var j = (i+p) %n ;
		if ( ray[j] > ray[j+1]) {
			return false;
		}

	}

	return true ;

}


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function gcd(a, b) {
    if (b == 0)
        return a;
    return gcd(b, a % b);
}

function abs(a) {
    return Math.max(a, -a);
}
function main() {
    let t = Number(readline())
    for (let j = 1; j <= t; j++) {
        let is = 0
        const map = new Map()
        let n = Number(readline())
        let a = readline().split(' ').map(Number)
        for (let i = 0; i < n; i++) {
            if (map.has(a[i]))
                map.set(a[i], map.get(a[i]) + 1)
            else
                map.set(a[i], 1)
            if (map.get(a[i]) >= n / 2)
                is = 1
        }
        if (is) {
            console.log(-1)
            continue
        }
        let ans = 0
        for (let i = 0; i < n; i++) {
            for (let j = i + 1; j < n; j++) {
                let big = abs(a[i] - a[j])
                for (let cand = 1; cand * cand <= big; cand++) {
                    let count = 0
                    if (big % cand) continue;
                    for (let k = 0; k < n; k++) {
                        if (abs(a[i] - a[k]) % cand) continue;
                        count++
                    }
                    if (count >= n / 2)
                        ans = Math.max(cand, ans)
                    count = 0
                    let cand1=big/cand
                    if (big % cand1) continue;
                    for (let k = 0; k < n; k++) {
                        if (abs(a[i] - a[k]) % cand1) continue;
                        count++
                    }
                    if (count >= n / 2)
                        ans = Math.max(cand1, ans)
                }
            }
        }
        console.log(ans)
    }
}

'use strict';
process.stdin.resume();
process.stdin.setEncoding('ascii');
let input = '';
process.stdin.on('data', (data) => {
    input += data;
});
process.stdin.on('end', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
class Scanner {
    constructor(input) {
        this.words = [];
        this.pos = 0;
        input.split('\n').forEach((line) => {
            this.words.push.apply(this.words, line.split(' ').filter(s => s != ''));
        });
    }
    nextInt() {
        return Math.floor(Number(this.words[this.pos++]));
    }
    nextBigInt() {
        return BigInt(this.nextInt());
    }
    nextStr() {
        return this.words[this.pos++];
    }
    eof() {
        return this.pos >= this.words.length;
    }
}
function af(l) {
    return Array.from({ length: l });
}
const INF = Number.MAX_SAFE_INTEGER;
const INIT = -1;
let n;
let a;
function same() {
    let cnt = new Map();
    for (let i = 0; i < n; i++) {
        cnt.set(a[i], (cnt.get(a[i]) || 0) + 1);
    }
    for (let [k, v] of cnt) {
        if (v * 2 >= n) {
            return true;
        }
    }
    return false;
}
function main() {
    const sc = new Scanner(input);
    let tc = sc.nextInt();
    while (tc-- > 0) {
        n = sc.nextInt();
        a = af(n);
        for (let i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        if (same()) {
            process.stdout.write(`-1\n`);
            continue;
        }
        let divs = [];
        for (let i = 0; i < n; i++) {
            for (let j = i + 1; j < n; j++) {
                let diff = Math.abs(a[i] - a[j]);
                for (let k = 1; k * k <= diff; k++) {
                    if ((diff % k) == 0) {
                        divs.push(diff / k);
                        divs.push(k);
                    }
                }
            }
        }
        divs = Array.from(new Set(divs));
        let ans = 0;
        for (let div of divs) {
            for (let i = 0; i < n; i++) {
                let cnt = 0;
                for (let j = 0; j < n; j++) {
                    let diff = Math.abs(a[i] - a[j]);
                    if ((diff % div) == 0) {
                        cnt++;
                    }
                }
                if (cnt * 2 >= n) {
                    ans = Math.max(ans, div);
                }
            }
        }
        process.stdout.write(`${ans}\n`);
    }
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        map[x] = (map[x] || 0) + 1
        if (map[x] >= n / 2) return -1
    }

    let ans = -1
    for (let i = 0; i < arr.length; i++) {
        // set arr[i] as target
        const ds = []
        for (let j = 0; j < arr.length; j++) {
            ds[j] = arr[j] - arr[i]
        }
        // try each possible gcd
        const gs = {}
        for (let j = 0; j < arr.length; j++) {
            if (ds[j] <= 0) continue
            gs[ds[j]] = 1

            for (let k = 0; k < arr.length; k++) {
                if (k === i || k === j || ds[k] <= 0) continue

                const g = gcd(ds[j], ds[k])
                gs[g] = 1
            }
        }
        for (let g in gs) {
            g = +g
            if (g > ans) {
                let count = map[arr[i]] // already
                for (let x = 0; x < arr.length; x++) {
                    if (ds[x] <= 0 || (ds[x] % g)) continue
                    count++
                }
            // console.log(`target=${arr[i]} g=${g} count=${count}`)
                if (count >= n / 2) ans = g
            }
        }
    }
    return ans
}
function gcd(a, b) {
    if (a === 0) return b
    if (b === 0) return a

    while (a) {
        const r = b % a
        b = a
        a = r
    }
    return b
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        map[x] = (map[x] || 0) + 1
        if (map[x] >= n / 2) return -1
    }

    let ans = -1
    for (let i = 0; i < arr.length; i++) {
        // set arr[i] as target
        const ds = []
        for (let j = 0; j < arr.length; j++) {
            ds[j] = arr[j] - arr[i]
        }
        // try each possible gcd
        const gs = {}
        for (let j = 0; j < arr.length; j++) {
            for (let k = 0; k < arr.length; k++) {
                if (k === i || k === j || ds[j] <= 0) continue

                const g = gcd(ds[j], ds[k])
                gs[g] = 1
            }
        }
        for (let g in gs) {
            g = +g
            if (g > ans) {
                let count = map[arr[i]] // already
                for (let x = 0; x < arr.length; x++) {
                    if (ds[x] <= 0 || (ds[x] % g)) continue
                    count++
                }
            // console.log(`target=${arr[i]} g=${g} count=${count}`)
                if (count >= n / 2) ans = g
            }
        }
    }
    return ans
}
function gcd(a, b) {
    if (a === 0) return b
    if (b === 0) return a

    while (a) {
        const r = b % a
        b = a
        a = r
    }
    return b
}


'use strict';

function solve(n, m, s) {
  const sum = new Array(n);
  for (let i = 0; i < n; i++) {
    var _sum;
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + (s[i] === 'B' ? 0 : 1);
  }
  let res = Infinity;
  for (let i = m - 1; i < n; i++) {
    var _sum2;
    res = Math.min(res, sum[i] - ((_sum2 = sum[i - m]) !== null && _sum2 !== void 0 ? _sum2 : 0));
  }
  return res;
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const [n, m] = (await read()).split(' ').map(Number);
      const s = await read();
      res.push(solve(n, m, s));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', () => {
  inputs = str.split('\n').values();
  main(read);
});

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  const gcd = (a, b) => (a % b === 0 ? b : gcd(b, a % b));
  let t = parseInt(readline());
  while (t--) {
       let [n,k] = readline().trim().split(" ").map(cur=>parseInt(cur));
       let arr = readline().trim().split("");
       let min = Infinity,i=0,cnt = 0,j=0;
       while(i<k) if(arr[i++]==="W") cnt++;
       min = Math.min(min,cnt);
       let l;
       while(i<n){
            l = cnt;
            if(arr[i]==="W") l++;
            if(arr[j]==="W") l--;
            min = Math.min(l,min);
            cnt = l;
            i++;
            j++;
       }
       console.log(min);
  }
};
solve();

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');

let currentline = 0;
function readline(){
    return input[currentline++];
}

let t = +readline();

while(t--){
    let [n , k] = readline().trim().split(' ').map(x=>+x);
    let str = readline().trim();
    console.log(`${solve(str, n, k)}`)
}

function solve(str, n, k){
    let result = n;
    let currW = 0;
    for(let i = 0; i < n; i++){
        if(str[i] === 'W') currW++;

        if(i-k +1 >= 0){
            result = Math.min(result, currW);
            if(str[i-k+1] === "W") currW--;
        }
        if(result === 0) break;
    }
    return result;
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const str = lines[l++]
        output[i] = solve(n, k, str)
    }
    console.log(output.join('\n'))
// })()
})

let F
function inc(idx, val) {
    for (; idx < F.length; idx |= idx + 1) {
        F[idx] += val
    }
}
function sum(idx) {
    let s = 0
    for (; idx >= 0; idx = (idx & (idx + 1)) - 1) {
        s += F[idx]
    }
    return s
}

function solve(n, k, str) {
    F = Array(n + 5).fill(0)
    for (let i = 0; i < str.length; i++) {
        if (str[i] === 'B') {
            inc(i, 1)
        }
    }
    let ans = Infinity
    for (let i = 0; i + k - 1 < str.length; i++) {
        // [i, i + k - 1]
        const d = sum(i + k - 1) - (i ? sum(i - 1) : 0)
        // console.log(i, k - d)
        ans = Math.min(ans, k - d)
    }
        // console.log('-')
    return ans
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var K = nextInt();
		var list = next();
		var sum = new Array(N + 1).fill(0);
		for(var i = 0; i < N; i++){
			if(list[i] == "W"){
				sum[i + 1]++;
			}
			sum[i + 1] += sum[i];
		}
		var output = 1000000000;
		for(var i = 0; i < N - K + 1; i++){
			output = Math.min(output, sum[i + K] - sum[i]);
		}
		myout(output);
	}
}

var tests = parseInt(readline());
    var n, k;
    var s;
    for (var t=0; t < tests; t++) {
        var nk = readline().split(' ').map(x=>parseInt(x));
        n = nk[0];
        k = nk[1];
        var s = readline();
        var dict = {
            B: 0,
            W: 0,
        }
        for (var i = 0; i < k; i++) {
            dict[s.charAt(i)]++;
        }
        var minW = dict.W;
        for (var i = k; i < n; i++) {
            dict[s.charAt(i)]++;
            dict[s.charAt(i-k)]--;
            if (dict.W < minW) {
                minW = dict.W;
            }
        }
        print(minW);
    }


var pearlsAmount = readline();
var typesOfPearls = readline().split(' ');
var segmentsEndPoints = [];
var amountOfSegments = 0;
var typesExistence = [];
for (var i = 0; i < pearlsAmount; i++) {
    if (typesExistence[typesOfPearls[i]]) {
        amountOfSegments++;
        segmentsEndPoints.push(i+1);
        typesExistence.length = 0;
    } else {
        typesExistence[typesOfPearls[i]] = 1;
    }
}

if (amountOfSegments == 0) {
    print("-1");
} else {
    segmentsEndPoints.pop();
    segmentsEndPoints.push(pearlsAmount);
    print(amountOfSegments);
    var startPoint = 1;
    for (var i = 0; i < amountOfSegments; i++) {
        print(startPoint + " " + segmentsEndPoints[i]);
        startPoint = segmentsEndPoints[i] + 1;
    }
}

var pearlsAmount = readline();
var typesOfPearls = readline().split(' ');
var segmentsEndPoints = [];
var amountOfSegments = 0;
var typesExistence = [];
for (var i = 0; i < pearlsAmount; i++) {
    if (typesExistence[typesOfPearls[i]]) {
        amountOfSegments++;
        segmentsEndPoints.push(i+1);
        typesExistence = [];
    } else {
        typesExistence[typesOfPearls[i]] = 1;
    }
}

if (amountOfSegments == 0) {
    print("-1");
} else {
    segmentsEndPoints.pop();
    segmentsEndPoints.push(pearlsAmount);
    print(amountOfSegments);
    var startPoint = 1;
    for (var i = 0; i < amountOfSegments; i++) {
        print(startPoint + " " + segmentsEndPoints[i]);
        startPoint = segmentsEndPoints[i] + 1;
    }
}

var n = readline();
var pearls = readline().split(' ');

var counter = [];

var result = [];
var rLength = 0;

var i;
var start_idx = 0;

pearls.map(function(x, idx) {
    x = parseInt(x, 10);
    if(!counter[x]) {
        counter[x] = 1;
    } else {
        result[rLength] = [start_idx + 1, idx +1];
        start_idx = idx + 1;
        rLength = rLength + 1;
        counter = [];
    }
});

if (rLength == 0) {
    print("-1");
}
else {
    result[rLength-1][1] = parseInt(n, 10);

    print(rLength);
    for (i = 0; i < rLength; i++){
        print(result[i][0]+ ' ' + result[i][1]);
    }
}

var pearlsAmount = readline();
var typesOfPearls = readline().split(' ');
var segmentsEndPoints = [];
var amountOfSegments = 0;
var object = {};
for (var i = 0; i < pearlsAmount; i++) {
    if (object[typesOfPearls[i]]) {
        amountOfSegments++;
        segmentsEndPoints.push(i+1);
        object = {};
    } else {
        object[typesOfPearls[i]] = 1;
    }
}

if (amountOfSegments == 0) {
    print("-1");
} else {
    segmentsEndPoints.pop();
    segmentsEndPoints.push(pearlsAmount);
    print(amountOfSegments);
    var startPoint = 1;
    for (var i = 0; i < amountOfSegments; i++) {
        print(startPoint + " " + segmentsEndPoints[i]);
        startPoint = segmentsEndPoints[i] + 1;
    }
}

var n = readline();
var pearls = readline().split(' ');

var counter = [];

var result = [];
var rLength = 0;

var i;
var start_idx = 0;

pearls.map(function(x, idx) {
    x = parseInt(x, 10);
    if(!counter[x]) {
        counter[x] = 1;
    } else {
        result[rLength] = [start_idx + 1, idx +1];
        start_idx = idx + 1;
        counter = [];
    }
});

if (rLength == 0) {
    print("-1\r\n");
}
else {
    result[rLength-1][1] = parseInt(n, 10);

    print("rLength\r\n");
    for (i = 0; i < rLength; i++){
        print("result[i][0] result[i][1]\n");
    }
}

var n = readline();
var pearls = readline().split(' ');

var counter = [];

var result = [];
var rLength = 0;

var i;
var start_idx = 0;

pearls.map(function(x, idx) {
    x = parseInt(x, 10);
    if(!counter[x]) {
        counter[x] = 1;
    } else {
        result[rLength] = [start_idx + 1, idx +1];
        start_idx = idx + 1;
        rLength = rLength + 1;
        counter = [];
    }
});

if (rLength == 0) {
    print("-1\r\n");
}
else {
    result[rLength-1][1] = parseInt(n, 10);

    print("rLength\r\n");
    for (i = 0; i < rLength; i++){
        print("result[i][0] result[i][1]\n");
    }
}

/*
 #include <stdio.h>
 int main(void) {
 int i;
 int start_idx = 0;

 scanf("%d", &n);

 for (i = 0; i < n; i++) {
 scanf("%d", &pearls[i]);

 if (increase_count(pearls[i]) == 0) {
 insert_new_pearl(pearls[i]);
 }
 else { // 2개가 되는 순간임
 result[result_length][0] = start_idx + 1;
 result[result_length++][1] = i + 1;
 start_idx = i + 1;
 length = 0;
 }
 }

 result[result_length-1][1] = n;

 if (result_length == 0) {
 printf("-1\n");
 }
 else {
 printf("%d\n", result_length);

 for (i = 0; i < result_length; i++){
 printf("%d %d\n", result[i][0], result[i][1]);
 }
 }

 return 0;
 }
 */