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 = true;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , len ;
        res = 0 ;
        len = this.s.length ;
        for( i = 0 ; i < len ; i++ ) {
        	if( i % 2 == 0 ) {
        		this.arr[ ( this.s.charCodeAt( i ) - 'a'.charCodeAt( 0 ) ) ]++ ;
        	}
        	else {
        		if( this.arr[ ( this.s.charCodeAt( i ) - 'A'.charCodeAt( 0 ) ) ] > 0 ) {
        			this.arr[ ( this.s.charCodeAt( i ) - 'A'.charCodeAt( 0 ) ) ]-- ;
        		}
        		else {
        			res++ ;
        		}
        	}
        }
        print( res );
    };

    this.init = function() {
        this.lim1 = 30;
        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();
            this.s = irObj.nextString();
        }
        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 cnt = new Array(26);
for(var i=0;i<26;i++)
    cnt[i] = 0;
var n = parseInt(readline());
var s = readline();
var ans = 0;
for(var i=0;i<2*n-2;i+=2) {
    var c = s[i].charCodeAt() - 97;
    cnt[c] ++;
    var c = s[i+1].charCodeAt() - 65;
    if(cnt[c] > 0) cnt[c] --;
    else ans ++;
}
print(ans);

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

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

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

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

  main();
});
// main();

////////////////////////////////////////////////////////////////////////

function main() {
  var a = readline();
  var b = readline().toLocaleLowerCase();
  let counter = 0; //bought keys
  let keys = {}; //key status
  for (let i = 0; i < b.length; i += 2) {
    //first step
    if (keys[b[i]] === undefined) {
      keys[b[i]] = 1;
    } else {
      keys[b[i]]++;
    }
    //second step
    if (keys[b[i + 1]]) {
      keys[b[i + 1]]--;
    } else {
      counter++;
    }
  }
  console.log(counter);
}

var n = +readline(), s = readline().split("");
var keys = {}, cnt = 0;

for(i = 0; i < s.length; i += 2){
	if(keys[s[i]] == undefined){
		keys[s[i]] = 1;
	}
	else{
		keys[s[i]]++;
	}

	if(keys[s[i+1].toLowerCase()] != undefined && keys[s[i+1].toLowerCase()] > 0){
		keys[s[i+1].toLowerCase()]--;
	}
	else{
		cnt++;
	}
}

write(cnt);

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 , len , len2 ;
        len = this.s.length ;
        res = "" ;
        for( i = 0 ; i < this.n ; i++ ) {
        	this.arr[ i ] = this.arr[ i ] - 1 ;
        }
        this.arr.sort() ;
        for( i = 0 ; i < len ; i++ ) {
        	this.brr[ i ] = this.s.charCodeAt( i ) ;
        }
        j = 0 ;
        cn = 0 ;
        len2 = Math.floor( len / 2 ) ;
        for( i = 0 ; i < len2 ; i++ ) {
        	while( j < this.n && this.arr[ j ] == i ) {
        		cn++ ;
        		j++ ;
        	}
        	if( cn % 2 == 0 ) {
        	}
        	else {
        		temp = this.brr[ i ] ;
        		this.brr[ i ] = this.brr[ len - i - 1 ] ;
        		this.brr[ len - i - 1 ] = temp ;
        	}
        }
        for( i = 0 ; i < len ; i++ ) {
        	res += String.fromCharCode( this.brr[ i ] ) ;
        }
        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.s = irObj.nextString();
            this.n = irObj.nextInt();
            this.arr = new Array() ;
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr.push( 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 cnt = new Array(26);
for(var i=0;i<26;i++)
    cnt[i] = 0;
var n = parseInt(readline());
var s = readline();
var ans = 0;
for(var i=0;i<2*n-2;i+=2) {
    var c = parseInt(s[i]) - parseInt('a');
    cnt[c] ++;
    var c = parseInt(s[i+1]) - parseInt('A');
    if(cnt[c] > 0) cnt[c] --;
    else ans ++;
}
print(ans);


var n = +readline();
var ans, i = 1, j = Math.pow(n,2);

for(k = 0; k < n; k++){
	for(ans = []; ; i++, j--){
		ans.push(i,j);
		if(ans.length == n){
			print(ans.join(" "));
			i++, j--;
			break;
		}
	}
}

;(function () {

	var n = +readline();
	var f1 = n*n;
	var f2 = 1;

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

		while (t.length < n) {
			t.push(f1--);
			t.push(f2++);
		}

		print(t.join(' '));
	}

}).call(this);

;(function () {

	var n = +readline();
	var o = {
		_min: 1,
		_max: n*n,
		max: function () { return this._max--; },
		min: function () { return this._min++; }
	}

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

		while (t.length < n) {
			t.push(o.min());
			t.push(o.max());
		}

		print(t.join(' '));
	}

}).call(this);

// 334A     Пакетики с конфетами

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var out = '';
var n2 = n * n;
var n2_2 = n2 / 2;

for (var i = 1; i <= n; i++) {
    for (var j = i; j <= n2_2; j+=n) {
        out += j.toString() + ' ' + (n2-j+1).toString() + ' ';
    };
    out += '\n';
};

print(out);

var n=+readline();
var ans=[];
for(var i=0;i<n;i++){
	ans.push([]);
}
for(var i=0,j=n*n; i<n*n/2; i++,j--){
	ans[i%n].push(i+1,j);
}
ans.forEach(function(v){
	print(v.join(' '));
});

var n = +readline();

for(var i = 1, j = Math.pow(n,2); i <= n; i++, j--){
	write(i + " " + j + "\n");
}

;(function () {

	var n = +readline();
	var s = (1 + n*n)*n/2;
	var o = {
		max: function () {
			for (var i = n*n; i > 0; i--)
				if (!(this[i])) {
					this[i] = true;
					return i;
				}
		}
	}

	var t, sum;
	for (var i = 0; i < n; i++) {
		sum = o.max();
		t = [sum];
		d = sum;

		while (sum != s) {
			--d;
			if (!o[d] && (sum + d) <= s) {
				o[d] = true;
				sum += d;
				t.push(d);
			}
		}

		print(t.join(' '));
	}

}).call(this);

// 334A     Пакетики с конфетами

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var out = '';
var n2 = n * n;
var n2_2 = n2 / 2;

for (var i = 1; i <= n; i++) {
    for (var j = i; j <= n2_2; j+=n) {
        out += j.toString() + ' ' + (n-j+1).toString() + ' ';
    };
    out += '\n';
};

print(out);


function getBeforeStep (i, k) {
  return i < k ? i : k;
}

function getAfterStep (i, k, n) {
  return i + k >= n ? (n - i) - 1 : k;
}

function getStep (i, k, n) {
  return getBeforeStep(i, k) + getAfterStep(i, k, n) + 1;
}

var input = readline();
var messages = readline().split(' ');

input = input.split(' ');
var n = parseInt(input[0]);
var k = parseInt(input[1]);

var i, value, lastValue, start, end, prevEnd, step;

for (i = 0; i < n; i++) {
  value = parseInt(messages[i]) - 1;
  lastValue = messages[value] || 0;

  start = Math.max(i - k, 0);
  end = i + getAfterStep(i, k, n);
  prevEnd = value + getAfterStep(value, k, n);

  step = i != 0 && value >= 0 && start <= prevEnd ? end - prevEnd : getStep(i, k, n);

  messages[i] = lastValue + step
}

print(messages.join(' '))

var input = readline().split(' ');
var n = +input[0];
var k = +input[1];
var refs = readline().split(' ').map(function (msg) {
  return +msg;
});
// const n = 20;
// const k = 1;
// const refs = [0, 1, 0, 3, 4, 5, 2, 3, 7, 0, 0, 7, 0, 3, 4, 12, 2, 3, 7, 0];

// Solution
function isRange(arr) {
  return Array.isArray(arr) && typeof arr[0] === 'number';
}

function checkCrossing(arr1, arr2) {
  if (arr1[1] >= arr2[0] && arr1[1] <= arr2[1]) {
    return 'left';
  }
  if (arr1[0] >= arr2[0] && arr1[0] <= arr2[1]) {
    return 'right'
  }
  return 'no';
}

function concatRanges(arr1, arr2) {
  return [
    arr1[0],
    arr2[1]
  ];
}

function getMessages(i) {
  if (refs[i] === 0) {
    return cache[i]; // Get numbers from cache
  }
  var refRange = getMessages(refs[i] - 1);

  // If refRange is like [2, 15]
  if (isRange(refRange)) {
    switch (checkCrossing(refRange, cache[i])) {
      case 'left':
        return concatRanges(refRange, cache[i]);
      case 'right':
        return concatRanges(cache[i], refRange);
      case 'no':
        if (cache[i][0] < refRange[0]) {
          return [cache[i], refRange];
        }
        return [refRange, cache[i]];
    }
  }

  // If refRange kinda [[1, 15], [18, 25]]
  var hasCrossing = false;
  var stopCheck = false;

  for (var k = 0, l = refRange.length; k < l; k++) {
    switch (checkCrossing(refRange[k], cache[i])) {
      case 'left':
        hasCrossing = true;
        refRange[k] = concatRanges(refRange[k], cache[i]);
        break;
      case 'right':
        hasCrossing = true;
        refRange[k] = concatRanges(cache[i], refRange[k]);
        break;
      case 'no':
        // To prevent excess entries
        if (cache[i][1] < refRange[k][0]) {
          stopCheck = true;
        }
        break;
    }
    if (hasCrossing || stopCheck) {
      break;
    }
  }

  if (!hasCrossing) {
    refRange.push(cache[i]);
  }
  return refRange;
}

var res = [];
var cache = [];

for (var ref = 0; ref < n; ref++) {
  cache[ref] = [
    ref - k < 0 ? 0 : ref - k, // Left border
    ref + k >= n ? n - 1 : ref + k // Right border
  ];
}

refs.forEach(function (ref, i) {
  var borders = getMessages(i);

  if (isRange(borders)) {
    res.push(borders[1] - borders[0] + 1);
  } else {
    var sum = 0;

    borders.forEach(function (border) {
      sum += border[1] - border[0] + 1;
    });
    res.push(sum);
  }
});

print(res.join(' '));

var numbers = readline().split(" ").map(function(x) { return parseInt(x); });
var messageHistory = readline().split(" ").map(function(x) { return parseInt(x); });
var visibleMessages = [], N = numbers[0], K = numbers[1];

for(var t = 0; t < N; t++) {
    var maxNumOfUniqueMessages = Math.min(N,
        Math.min(K, t) + 1 + Math.min(K, N - t - 1)
    );

    if(t <= K) {
        visibleMessages[t] = Math.min(
            t + 1 + K,
            maxNumOfUniqueMessages
        );
    } else {
        var linkToPrevMessage = messageHistory[t] - 1;
        var intersectionNumber = (Math.min(linkToPrevMessage + K + 1, N) - (t - K));
        intersectionNumber = intersectionNumber > 0 ? intersectionNumber : 0;

        visibleMessages[t] = linkToPrevMessage >= 0 ?
            visibleMessages[linkToPrevMessage] +
            (maxNumOfUniqueMessages - intersectionNumber):
            maxNumOfUniqueMessages;
   }
}

write(visibleMessages.join(' '));

function getStep (i, k, n) {
  var before = k;
  var after = k;
  if (i < k) {
    before = +(0 - i);
  }
  if (i + k >= n) {
    after = (n - i) - 1;
  }

  return before + after + 1;
}

var input = readline();
var messages = readline().split(' ');

input = input.split(' ');
var n = parseInt(input[0]);
var k = parseInt(input[1]);

var i, lastValue, step, diff, value;

for (i = 0; i < n; i++) {
  value = parseInt(messages[i]) - 1;
  lastValue = messages[value] || 0;
  step = getStep(i, k, n);
  diff = i - value - 1;

  if (value >= 0 && k > 0 && diff < step) {
    step = i - value + k - 1
  }
  messages[i] = lastValue + step
}

print(messages.join(' '))

function getIndexesRange (index, k, arr) {
  var range = [];
  var start =  Math.max(index - k, 0);
  var end = Math.min(index + k + 1, arr.length);
  for (var i = start; i < end ; i++) {
    range.push(i);
  }
  return range;
}

var input = readline();
var messages = readline().split(' ');

input = input.split(' ');
var n = parseInt(input[0]);
var k = parseInt(input[1]);

var i, value, range, prevIndex, readedMessages;
var map = {};
var messagesCounts = [];

for (i = 0; i < n; i++) {
  value = messages[i] = parseInt(messages[i]);
  readedMessages = [];

  prevIndex = value - 1;
  if (prevIndex > 0) {
    readedMessages = readedMessages.concat(map[prevIndex]);
  }

  range = getIndexesRange(i, k, messages);

  range.forEach(function (v) {
    if (readedMessages.indexOf(v) == -1) {
      readedMessages.push(v);
    }
  })

  map[i] = readedMessages;
  messagesCounts.push(readedMessages.length);
}

print(messagesCounts.join(' '))

function getBeforeStep (i, k) {
  return i < k ? +(0 - i) : k;
}

function getAfterStep (i, k, n) {
  return i + k >= n ? (n - i) - 1 : k;
}

function getStep (i, k, n) {
  return getBeforeStep(i, k) + getAfterStep(i, k, n) + 1;
}

var input = readline();
var messages = readline().split(' ');

input = input.split(' ');
var n = parseInt(input[0]);
var k = parseInt(input[1]);

var i, value, lastValue, start, end, prevEnd, step;

for (i = 0; i < n; i++) {
  value = parseInt(messages[i]) - 1;
  lastValue = messages[value] || 0;

  start = Math.max(i - k, 0);
  end = i + getAfterStep(i, k, n);
  prevEnd = value + getAfterStep(value, k, n);

  step = i != 0 && value >= 0 && start <= prevEnd ? end - prevEnd : getStep(i, k, n);

  messages[i] = lastValue + step
}

print(messages.join(' '))

function getBeforeStep (i, k) {
  return i < k ? +(0 - i) : k;
}

function getAfterStep (i, k, n) {
  return i + k >= n ? (n - i) - 1 : k;
}

function getStep (i, k, n) {
  return getBeforeStep(i, k) + getAfterStep(i, k, n) + 1;
}

var input = readline();
var messages = readline().split(' ');

input = input.split(' ');
var n = parseInt(input[0]);
var k = parseInt(input[1]);

var i, value, lastValue, start, end, prevEnd, step;

for (i = 0; i < n; i++) {
  value = parseInt(messages[i]) - 1;
  lastValue = messages[value] || 0;

  start = i - getBeforeStep(i, k);
  end = i + getAfterStep(i, k, n);
  prevEnd = value + getAfterStep(value, k, n);

  step = i != 0 && start <= prevEnd ? end - prevEnd : getStep(i, k, n);

  messages[i] = lastValue + step
}

print(messages.join(' '))


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

let s = "";

process.stdin.on("data", (data) => {
  s += data;
});

process.stdin.on("end", (data) => {
  s = s.split("\n").filter(Boolean);

  main();
});

function main() {
  const t = Number(s[0]);

  let i = 1;
  while (i < 3 * t + 1) {
    const length = s[i++];
    const a = s[i++].split(" ").map(Number);
    const b = s[i++].split(" ").map(Number);

    solve(a, b);
  }
}

function solve(a, b) {
  function recurse(a, b, index) {
    if (index > a.length - 1) {
      return;
    }

    if (a[index] < b[index]) {
      swap(a, b, index);
    }

    recurse(a, b, index + 1);
  }

  recurse(a, b, 0, 0);
  console.log(doSum(a, b));
}

function swap(a, b, index) {
  const temp = a[index];
  a[index] = b[index];
  b[index] = temp;
}

function doSum(a, b) {
  let sum = 0;
  for (let i = 0; i < a.length - 1; i++) {
    sum += Math.abs(a[i] - a[i + 1]);
    sum += Math.abs(b[i] - b[i + 1]);
  }
  return sum;
}

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}
const l = process.env.DEBUG ? console.log : ()=>{};

module.exports = E;

const ra = ()=>readline().split(' ').map(a=>+a)

const MOD = 1e9+7;

const calc = (a, b, n)=>{
  let swap = (i)=>{
    let tmp = a[i];
    a[i] = b[i];
    b[i] = tmp;
  }
  let sum = 0;
  for (let i=1; i<n; i++){
    let v1 = Math.abs(a[i]-a[i-1])+Math.abs(b[i-1]-b[i]);
    let v2 = Math.abs(a[i]-b[i-1])+Math.abs(a[i-1]-b[i]);
    sum += Math.min(v1, v2)
  }
  return sum;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let a = ra();
      let b = ra();
      l('ans')
      print(calc(a, b, n));
    }
}

E.calc = calc;

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    var a = 0;
    for(i = 1; i <= t * 3; i++){
        var b = lines[i].split(' ').map(Number);
        if(i % 3 == 1){
            n = lines[i];
        }else if(i % 3 == 2){
            a = b;
        }else{
            var ans = 0;
            for(j = 1; j < n; j++){
                var x = Math.abs(a[j] - a[j - 1]) + Math.abs(b[j] - b[j - 1]);
                var y = Math.abs(a[j] - b[j - 1]) + Math.abs(b[j] - a[j - 1]);
                ans += Math.min(x, y);
            }
            console.log(ans);
        }
    }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);
        let brr = readline().split(' ').map(Number);

        const calc = i => Math.abs(arr[i-1] - arr[i]) + Math.abs(brr[i-1] - brr[i]);

        let sum = 0;
        for (let i = 1; i < n; i++) {
            let cur = calc(i);
            let alt = Math.abs(arr[i-1] - brr[i]) + Math.abs(brr[i-1] - arr[i]);
            if (alt < cur) [arr[i], brr[i]] = [brr[i], arr[i]];
            sum += Math.min(alt, cur);
        }

        output(sum);
    }
}

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 a = lines[l++].trim().split(' ').map(Number)
        const b = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, a, b)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, a, b) {
    for (let i = 0; i < a.length; i++) {
        if (a[i] > b[i]) {
            [a[i], b[i]] = [b[i], a[i]]
        }
    }
    let ans = 0
    for (let i = 1; i < a.length; i++) {
        ans += Math.abs(a[i] - a[i - 1])
        ans += Math.abs(b[i] - b[i - 1])
    }
    // console.log(a, b)
    return ans
}

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let ls = [];

function solve() {
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let i = 0; i < t; i++) {
        const n = parseInt(ls[l++]);
        const a = ls[l++].split(' ').map(v => parseInt(v));
        const b = ls[l++].split(' ').map(v => parseInt(v));
        solveInner(n, a, b);
    }
}

function solveInner(n, a, b) {
    for (let i = 0; i < n - 1; i++) {
        const d1 = Math.abs(a[i] - a[i + 1]) + Math.abs(b[i] - b[i + 1]);
        const d2 = Math.abs(a[i] - b[i + 1]) + Math.abs(b[i] - a[i + 1]);
        if (d1 > d2) {
            [a[i + 1], b[i + 1]] = [b[i + 1], a[i + 1]];
        }
    }
    let sum = 0;
    for (let i = 0; i < n - 1; i++) {
        sum += Math.abs(a[i] - a[i + 1]);
        sum += Math.abs(b[i] - b[i + 1]);
    }
    console.log(sum);
}

rl.on('line', (l) => ls.push(l));
rl.on('close', () => solve());

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

function solve(n, a, b) {
  const dp = new Array(n).fill(0).map(() => [0, 0])
  for (let i = 1; i < n; i++) {
    dp[i][0] = Math.min(
      dp[i - 1][0] + Math.abs(a[i] - a[i - 1]) + Math.abs(b[i] - b[i - 1]),
      dp[i - 1][1] + Math.abs(a[i] - b[i - 1]) + Math.abs(b[i] - a[i - 1]),
    )
    dp[i][1] = Math.min(
      dp[i - 1][0] + Math.abs(b[i] - a[i - 1]) + Math.abs(a[i] - b[i - 1]),
      dp[i - 1][1] + Math.abs(a[i] - a[i - 1]) + Math.abs(b[i] - b[i - 1]),
    )
  }
  return Math.min(dp[n - 1][0], dp[n - 1][1])
}

void (function main() {
  const _ = Number(inputs[0])
  let res = []

  for (let __ = 0; __ < _; __++) {
    let n = Number(inputs[__ * 3 + 1])
    const a = inputs[__ * 3 + 2].trim().split(' ').map(Number)
    const b = inputs[__ * 3 + 3].trim().split(' ').map(Number)

    res.push(solve(n, a, b))
  }

  console.log(res.join('\n'))
})()

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

function div(val, by){
    return (val - val % by) / by;
}

const calc = (n, a, b)=>{
    let res = 0;
    for (let i = 1; i < n; i++) {
        let min = Math.abs(a[i] - a[i - 1]) + Math.abs(b[i] - b[i - 1]);
        min = Math.min(min, Math.abs(a[i] - b[i - 1]) + Math.abs(b[i] - a[i - 1]));
        res += min;
    }
    return res;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = ra();
        let b = ra();
        console.log(`${calc(n, a, b)}`);
    }
}

var t = +readline()

for(var i = 0; i< t; i ++) {
    var a = readline()
    var arr1 = readline().split(" ").map(x => +x);
    var arr2 = readline().split(" ").map(x => +x);
    print(getMinSum(arr1,arr2))
}

 function getMinSum(arr1,arr2){

    var ai = arr1[0];
    var bi = arr2[0];
    var sum = 0;
    for(var i = 1; i<arr1.length;i++){
        var s1 = Math.abs(arr1[i]-ai)+Math.abs(arr2[i]-bi);
        var s2 = Math.abs(arr2[i]-ai)+Math.abs(arr1[i]-bi);
        if (s1 > s2){
            sum += s2;
            ai = arr2[i];
            bi = arr1[i];
        }else {
            sum += s1;
            ai = arr1[i];
            bi = arr2[i];
        }
    }
    return sum;

}

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

let s = "";

process.stdin.on("data", (data) => {
  s += data;
});

process.stdin.on("end", (data) => {
  s = s.split("\n").filter(Boolean);

  main();
});

function main() {
  const t = Number(s[0]);

  let i = 1;
  while (i < 3 * t + 1) {
    const length = s[i++];
    const a = s[i++].split(" ").map(Number);
    const b = s[i++].split(" ").map(Number);

    solve(a, b);
  }
}

function solve(a, b) {
  function recurse(a, b, index) {
    if (index >= a.length - 1) {
      return;
    }

    if (a[index] < b[index]) {
      swap(a, b, index);
    }

    recurse(a, b, index + 1);
  }

  recurse(a, b, 0, 0);
  console.log(doSum(a, b));
}

function swap(a, b, index) {
  const temp = a[index];
  a[index] = b[index];
  b[index] = temp;
}

function doSum(a, b) {
  let sum = 0;
  for (let i = 0; i < a.length - 1; i++) {
    sum += Math.abs(a[i] - a[i + 1]);
    sum += Math.abs(b[i] - b[i + 1]);
  }
  return sum;
}

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}
const l = process.env.DEBUG ? console.log : ()=>{};

module.exports = E;

const ra = ()=>readline().split(' ').map(a=>+a)

const MOD = 1e9+7;

const calc = (a, b, n)=>{
  let swap = (i)=>{
    let tmp = a[i];
    a[i] = b[i];
    b[i] = tmp;
  }
  for (let i=1; i<n; i++){
    if (Math.abs(a[i]-a[i-1])>Math.abs(a[i-1]-b[i]))
      swap(i);
  }
  let sum = 0;
  for (let i=1; i<n; i++)
    sum += Math.abs(a[i]-a[i-1])+Math.abs(b[i-1]-b[i])

  return sum;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let a = ra();
      let b = ra();
      l('ans')
      print(calc(a, b, n));
    }
}

E.calc = calc;


'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n),
        b = rns(n);
  for (let i = 0; i < n; i++) {
    if (a[i] > b[i]) return 'NO';
  }
  for (let i = 0; i < n; i++) {
    if (b[i] > b[(i + 1) % n] + 1 && a[i] < b[i]) return 'NO';
  }
  return 'YES';
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\s+/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);
        let brr = readline().split(' ').map(Number);

        let next = (a, i) => {
            if (i === a.length - 1) {
                return a[0];
            } else {
                return a[i + 1];
            }
        }

        let no = false;
        for (let i = 0; i < n; i++) {
            if (arr[i] === brr[i]) {
                continue;
            }
            if (arr[i] > brr[i]) {
                no = true;
                break;
            }
            if (brr[i] > (next(brr, i) + 1)) {
                no = true;
                break;
            }
        }

        output(no ? 'NO' : 'YES');
    }
}

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let a = iInpArr();
    let b = iInpArr();
    const helper = (a, b) => {
      for (let i = 0; i < n; i++) {
        if (a[i] > b[i]) return false;
        if (a[i] !== b[i] && b[(i + 1) % n] + 1 < b[i]) return false;
      }
      return true;
    };
    console.log(helper(a, b) ? "YES" : "NO");
  }
};
solve();

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let a = iInpArr();
    let b = iInpArr();
    let flag = 1;
    for (let i = 0; i < n; i++) {
      if (a[i] !== b[i]) {
        flag = 0;
        break;
      }
    }
    if (flag === 1) {
      console.log("YES");
      continue;
    }
    flag = 1;
    for (let i = 0; i < n; i++) {
      if (b[i] < a[i]) {
        flag = 0;
        break;
      }
    }
    if (flag === 0) {
      console.log("NO");
      continue;
    }
    flag = 1;
    let max = a[n - 1];
    for (let i = n - 2; i >= 0; i--) {
      if (a[i] === b[i]) {
        max = a[i];
        continue;
      }
      if (b[i] <= max) {
        a[i] = b[i];
        max = b[i];
        continue;
      } else {
        if (a[i] <= max) a[i] = max;
        else max = a[i];
      }
    }
    for (let i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) continue;
      if (b[i] - 1 <= a[(i + 1) % n]) a[i] = b[i];
      else {
        flag = 0;
        break;
      }
    }

    if (flag === 0) console.log("NO");
    else console.log("YES");
  }
};
solve();

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let a = iInpArr();
    let b = iInpArr();
    let flag = 1;
    for (let i = 0; i < n; i++) {
      if (a[i] !== b[i]) {
        flag = 0;
        break;
      }
    }
    if (flag === 1) {
      console.log("YES");
      continue;
    }
    flag = 1;
    let max = a[n - 1];
    for (let i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) {
        max = a[i];
        continue;
      }
      if (a[i] < max && b[i] >= max) a[i] = max;
      max = Math.max(max, a[i]);
    }
    for (let i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) continue;
      if (i === n - 1) {
        if (a[i] > b[i]) {
          flag = 0;
          break;
        } else {
          let dif = b[i] - a[i];
          let dif2 = a[0] - a[i] + 1;
          if (dif > dif2) {
            flag = 0;
            break;
          } else {
            a[i] = b[i];
          }
        }
      } else {
        if (a[i] > b[i]) {
          flag = 0;
          break;
        } else {
          let dif = b[i] - a[i];
          let dif1 = a[i + 1] - a[i] + 1;
          if (dif > dif1) {
            flag = 0;
            break;
          } else a[i] = b[i];
        }
      }
    }
    if (flag === 1) {
      console.log("YES");
    } else {
      console.log("NO");
    }
  }
};
solve();

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let a = iInpArr();
    let b = iInpArr();
    let flag = 1;
    for (let i = 0; i < n; i++) {
      if (a[i] !== b[i]) {
        flag = 0;
        break;
      }
    }
    if (flag === 1) {
      console.log("YES");
      continue;
    }
    flag = 1;
    let max = a[n - 1];
    for (let i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) {
        max = a[i];
        continue;
      }
      if (a[i] < max && b[i] > max) a[i] = max;
      max = Math.max(max, a[i]);
    }
    for (let i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) continue;
      if (i === n - 1) {
        if (a[i] > b[i]) {
          flag = 0;
          break;
        } else {
          let dif = b[i] - a[i];
          let dif2 = a[0] - a[i] + 1;
          if (dif > dif2) {
            flag = 0;
            break;
          } else {
            a[i] = b[i];
          }
        }
      } else {
        if (a[i] > b[i]) {
          flag = 0;
          break;
        } else {
          let dif = b[i] - a[i];
          let dif1 = a[i + 1] - a[i] + 1;
          if (dif > dif1) {
            flag = 0;
            break;
          } else a[i] = b[i];
        }
      }
    }
    if (flag === 1) {
      console.log("YES");
    } else {
      console.log("NO");
    }
  }
};
solve();


const n = Number(readline());
const a = [1].concat(readline().split(" ").slice(0, n)).map(x => Number(x < 0));
for (var i = 1; i <= n; i++)
  a[i] += a[i - 1];
const counts = [0, 0];
for (var i = 0; i <= n; i++) {
  a[i] &= 1;
  counts[a[i]]++;
}
var negative = 0;
for (var i = 0; i <= n;) {
  var cur = a[i];
  var next = 1 - cur;
  var j = a.indexOf(next, i);
  if (j === -1) break;
  var diff = j - i;
  negative += diff * counts[next];
  counts[cur] -= diff;
  i = j;
}
print(`${negative} ${n * (n + 1) * 0.5 - negative}`);


var t = +readline();

for (var i=0; i<t; i++){
	var tn = readline().split(' ').map(Number);
	var n = tn[0];
	var x = tn[1];
	var y = tn[2];
	var d = tn[3];

	if ( Math.abs(y-x)%d == 0 ) print (Math.abs(y-x)/d);
	else if ( (y-1)%d == 0 && (n-y)%d == 0 ) {
		if ( (Math.ceil((x-1)/d) + (y-1)/d) < (Math.ceil((n-x)/d) + (n-y)/d) ) print ((Math.ceil((x-1)/d) + (y-1)/d));
		else print (Math.ceil((n-x)/d) + (n-y)/d);
	} else if ((y-1)%d == 0) print ((Math.ceil((x-1)/d) + (y-1)/d));
	  else if ((n-y)%d == 0) print (Math.ceil((n-x)/d) + (n-y)/d);
	else print (-1);
}

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let l = 0;
let n = 0

rl.on('line', (input) => {
    if (l === 0) {
        n = parseInt(input)
    } else {
        if (l === n)
            rl.close();

        let arr = input.split(" ").map(x => parseInt(x))
        // console.log((arr[1]-1)%arr[3])
        let max = 999999999999
        let ans1 = max
        let ans2 = max
        let ans3 = max
        if (Math.abs(arr[2] - arr[1]) % arr[3] === 0) {
            ans1 = Math.round(Math.abs(arr[2] - arr[1]) / arr[3])
        }
        if (Math.abs(arr[2] - 1) % arr[3] === 0) {
            let rest1 = Math.abs(arr[2] - 1) / arr[3]
            let rest2 = Math.abs(arr[1] - 1) / arr[3]
            ans2 = Math.round(rest1) + Math.ceil(rest2)

        }
        if (Math.abs(arr[0] - arr[2]) % arr[3] === 0) {
            let rest1 = Math.abs(arr[1] - arr[0]) / arr[3]
            let rest2 = Math.abs(arr[0] - arr[2]) / arr[3]
            ans3 = Math.ceil(rest1) + Math.round(rest2)
        }
        //console.log(ans1, ans2, ans3)
        let mn = Math.min(ans1, Math.min(ans2, ans3))
        console.log(mn === max ? -1 : mn)
    }
    l++
});

var t = readline();
for (var i=0; i<t; i++) {
    var input = readline().split(' ');
    var n = input[0];
    var x = input[1];
    var y = input[2];
    var d = input[3];
    if ((y - x) % d === 0) print(Math.abs(y - x) / d);
    else {
        if (((y - 1) % d) !=0 && ((n - y) % d) != 0) print(-1);
        else {
            var diffBeg = Math.ceil((x - 1) / d) + ( ((y - 1) % d) ===0 ? (y - 1) / d : 100000000000);
            var diffEnd = Math.ceil((n - x) / d) + ( ((n - y) % d) ===0 ? (n - y) / d : 100000000000);
            print( (diffBeg < diffEnd) ? diffBeg : diffEnd);
        }
    }
}

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let l = 0;
let n = 0

rl.on('line', (input) => {
    if (l === 0) {
        n = parseInt(input)
    } else {
        if (l === n)
            rl.close();

        let arr = input.split(" ").map(x => parseInt(x))
        if (Math.abs(arr[2] - arr[1]) % arr[3] === 0) {
            console.log(Math.floor(Math.abs(arr[2] - arr[1]) / arr[3]))
        } else if (Math.abs(Math.min(arr[2], arr[1]) - 2) % arr[3] === 0 &&
            Math.abs(Math.max(arr[2], arr[1]) - 1) % arr[3] === 0) {
            console.log(Math.floor(Math.max(arr[2], arr[1]) - 1 / arr[3]))
        } else
            console.log("-1")
    }
    l++
});

var t = readline();
for (var i=0; i<t; i++) {
    var input = readline().split(' ');
    var n = input[0];
    var x = input[1];
    var y = input[2];
    var d = input[3];
    if ((y - x) % d === 0) print((y - x) / d);
    else {
        if (((y - 1) % d) !=0 && ((n - y) % d) != 0) print(-1);
        else {
            var diffBeg = Math.ceil(x / d) + ( ((y - 1) % d) ===0 ? (y - 1) / d : 100000000000);
            var diffEnd = Math.ceil((n - x) / d) + ( ((n - y) % d) ===0 ? (n - y) / d : 100000000000);
            print( (diffBeg < diffEnd) ? diffBeg : diffEnd);
        }

    }
}

var t = readline();
for (var i=0; i<t; i++) {
    var input = readline().split(' ');
    var n = input[0];
    var x = input[1];
    var y = input[2];
    var d = input[3];
    if ((y - x) % d === 0) print((y - x) / d);
    else {
        if (((y - 1) % d) !=0 && ((n - y) % d) != 0) print(-1);
        else {
            var diffBeg = Math.ceil(x / d) + ( ((y - 1) % d) ===0 ? (y - 1) / d : 10000000000);
            var diffEnd = Math.ceil((n - x) / d) + ( ((n - y) % d) ===0 ? (n - y) / d : 10000000000);
            print( (diffBeg < diffEnd) ? diffBeg : diffEnd);
        }
    }
}

var t = readline();
for (var i=0; i<t; i++) {
    var input = readline().split(' ');
    var n = input[0];
    var x = input[1];
    var y = input[2];
    var d = input[3];
    if ((y - x) % d === 0) print((y - x) / d);
    else {
        if (((y - 1) % d) !=0 && ((n - y) % d) != 0) print(-1);
        else {
            var diffBeg = Math.ceil((x-1) / d) + ( ((y - 1) % d) ===0 ? (y - 1) / d : 100000000000);
            var diffEnd = Math.ceil((n - x) / d) + ( ((n - y) % d) ===0 ? (n - y) / d : 100000000000);
            print( (diffBeg < diffEnd) ? diffBeg : diffEnd);
        }

    }
}

var t = readline();
for (var i=0; i<t; i++) {
    var input = readline().split(' ');
    var n = input[0];
    var x = input[1];
    var y = input[2];
    var d = input[3];
    if ((x - y) % d === 0) print((x - y) / d);
    else {
        var diffBeg = ((y - 1) % d);
        var diffEnd = ((n - y) % d);
        if (diffBeg != 0 || diffEnd != 0) print(-1);
        else print( (diffBeg < diffEnd) ? (y - 1)/d : (n-y)/d);
    }
}


const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
// const n = parseInt(input[0], 10);
let secondLine = input[1].split(' ');
const nums = secondLine.map((a) => parseInt(a, 10));

if (nums.length <= 2) {
  console.log(0);
  return
}

let min = nums[0];
let max  = nums[0];
let cmin = 1;
let cmax = 1;
let result = 0;

for (let i=1; i< nums.length; i++) {
  const num = nums[i];
  const nmin = Math.min(min, num);
  if (nmin !== min) {
    if (min !== max) {
      result += cmin;
    }
    cmin = 1;
  }
  if (num === min) {
    cmin += 1;
  }
  const nmax = Math.max(max, num);
  if (nmax !== max) {
    if (min !== max) {
      result += cmax;
    }
    cmax = 1;
  }
  if (num === max) {
    cmax += 1;
  }
  if (nmin === min && nmax === max && nmax !== num && nmin !== num) {
    result += 1;
  }
// console.log({num ,min, nmin, max, nmax, result});
  min = nmin;
  max = nmax;
}
console.log(result);
});

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));
var res=0;
input.sort((a,b)=>a-b);
var small=input[0];
var big=input[n-1];

for(var i=1;i<=n-2;i++){
    if(input[i]>small && input[i]<big){
        res++;
    }
}

print(res);

function findMin(array){
    var mn = Infinity;
    for(var i=0;i<array.length;i++){
        mn=Math.min(array[i],mn)
    }
    return mn;
}

function findMax(array){
    var mx = -Infinity;
    for(var i=0;i<array.length;i++){
        mx=Math.max(array[i],mx);
    }
    return mx;
}

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));
var res=0;

var mn=findMin(input);
var mx=findMax(input);

for(var i=0;i<n;i++){
    if(input[i]>mn && input[i]<mx){
        res++;
    }
}

print(res);

var n = Number(readline()),
    stewards = readline().split(' ').map(Number).sort((a,b)=>a-b),
    counter = 0;

    big = stewards[stewards.length - 1],
    small = stewards[0];

for (var i = 1; i < stewards.length - 1; i++){

    if(stewards[i] > small && stewards[i] < big)
        counter++;

    // var count = i,
    //     thereIsBefore = false,
    //     thereIsAfter = false;
    // while(count > 0) {
    //     if(stewards[count - 1] < stewards[i]){
    //         thereIsBefore = true;
    //         break;
    //     }
    //     count--;
    // }
    // while(count < stewards.length - 1) {
    //     if(stewards[count + 1] > stewards[i]){
    //         thereIsAfter = true;
    //         break;
    //     }
    //     count++;
    // }
    // if(thereIsAfter && thereIsBefore)
    //     counter++;

}

print(counter);

function main(n,arr){

    var min  = Infinity;
    var max =  -Infinity;
    var cnt = 0;

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

      max = Math.max(max,arr[i]);
      min = Math.min(min,arr[i]);

    }

    for(var i = 0 ; i < n ; i++){
      if(arr[i] > min && arr[i] < max)cnt++;
    }

    print(cnt);
}

var n = parseInt(readline());

var arr = readline().split(' ');
for(var i = 0  ; i < arr.length ; i++)arr[i] = parseInt(arr[i]);

main(n,arr);

var n = parseInt(readline());
var p = readline().split(' ').map(function(x){
    return parseInt(x);
});
var minv = 1e9;
var maxv = -1e9;
p.forEach(function(x){
   minv = Math.min(minv, x);
   maxv = Math.max(maxv, x);
});
print(p.filter(function(x){
    return minv < x && x < maxv;
}).length);

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  stewardsStrength = stewardsStrength.sort((a, b) => a - b)

  var i = 1
  var count = 0
  while (i < numberOfSteward) {
    if (stewardsStrength[0] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[stewardsStrength.length - 1]) {
      count += 1
    }
    i++
  }

  print(count)

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  var weaker = Infinity
  var stronger = -Infinity
  for (var i = 0; i < numberOfSteward; i++) {
    weaker = Math.min(weaker, stewardsStrength[i])
    stronger = Math.max(stronger, stewardsStrength[i])
  }

  var count = 0
  for (var i = 0; i < numberOfSteward; i++) {
    if (weaker < stewardsStrength[i] && stewardsStrength[i] < stronger) {
      count += 1
    }
  }

  print(count)

var n = parseInt(readline())
var list = readline().trim().split(' ')
var min = 1e9+1, max = -1
var dict = {}
var total = list.length
for (var num of list) {
    num = parseInt(num)
    min = min > num ? num : min
    max = max < num ? num : max
    dict[num] = (dict[num] || 0) + 1
}

if (min === max) {
    print(0)
} else {
    print (total - dict[min] - dict[max])
}

var stuartsCount = +readline(),
    stuartsRaits = readline().split(/\s+/).slice(0, stuartsCount),
    minRait = Math.min.apply(null, stuartsRaits),
    maxRait = Math.max.apply(null, stuartsRaits);

print(
    stuartsRaits.reduce(function(count, rait){
        return (rait > minRait && rait < maxRait) ? count + 1 : count;
    }, 0)
);

// Generated by CoffeeScript 1.12.4
(function() {
  var count, max, min, stuarts;

  readline();

  stuarts = readline().split(" ").map(Number);

  min = stuarts[0];

  max = 0;

  count = 0;

  stuarts.forEach(function(num) {
    if (num < min) {
      min = num;
    }
    if (num > max) {
      return max = num;
    }
  });

  stuarts.forEach(function(num) {
    if (num > min && num < max) {
      return count++;
    }
  });

  write(count);

}).call(this);

console = {log: ()=>{}}
var count, max, min, stuarts;
readline();
stuarts = readline().split(" ").map(Number);
min = stuarts[0];
max = 0;
count = 0;
stuarts.forEach(function(num) {
  if (num < min) {
    min = num;
  }
  if (num > max) {
    return max = num;
  }
});
stuarts.forEach(function(num) {
  if (num > min && num < max) {
    return count++;
  }
});
write(count);

try {require("codeforces")} catch(e){console = {log: function(){}, error: function(){}}};

var count, max, min, stuarts;
readline();
stuarts = readline().split(" ").map(Number);
min = stuarts[0];
max = 0;
count = 0;
stuarts.forEach(function(num) {
    if (num < min) {
        min = num;
    }
    if (num > max) {
        return max = num;
    }
});
console.log("ssss");
stuarts.forEach(function(num) {
    if (num > min && num < max) {
        return count++;
    }
});
write(count);

var n = parseInt(readline());
var total = readline().split(" ").map(Number).sort((a, b) => a - b);

var count = total.length - 2;

for (var i = 0; i < total.length; i++) {
    if ((i !== 0 && total[i] === total[0]) ||
        (i !== total.length - 1 && total[i] === total[total.length - 1])) {
        count--;
    }
}

print(count < 0 ? 0: count);

'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 print(s) {
  process.stdout.write(`${s}`);
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  // input
  const n = +readline();
  let a = readline().split(' ').map(x => parseInt(x));
  let r = 0;
  if (a.length > 2) {
    let min = Number.MAX_SAFE_INTEGER, max = Number.MIN_SAFE_INTEGER;
    for (let i = 0; i < n; i++) {
      min = Math.min(min, a[i]);
      max = Math.max(max, a[i]);
    }
    for (let i = 0; i < n; i++) {
      if (a[i] > min && a[i] < max) {
        r++;
      }
    }
  }
  print(r);
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  let ans = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > min && arr[i] < max) {
      ans++;
    }
  }

  console.log(ans);

  c++;
});

'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 readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

function print(x) {
    console.log(x);
}

function write(x) {
    process.stdout.write(x);
}
function main() {
    let [n] = readint();
    let a = readint();
    let all = a.length;
    let mx = a[0];
    let mn = a[0];
    a.forEach(element => {
        if(mx < element) mx = element;
        if(mn > element) mn = element;
    });
    let mxcount = 0,
        mncount = 0;
    a.forEach(element => {
        if(element == mx) mxcount++;
        if(element == mn) mncount++;
    });
    if(mx != mn)
        print(a.length - mncount - mxcount);
    else
        print(a.length - mncount);
}

'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 readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

function print(x) {
    console.log(x);
}

function write(x) {
    process.stdout.write(x);
}
function main() {
    let [n] = readint();
    let a = readint();
    let all =a.length;
    let mx = a[0];
    let mn = a[0];
    a.forEach(element => {
        if(mx < element) mx = element;
        if(mn > element) mn = element;
    });
    let mxcount = 0,
        mncount = 0;
    a.forEach(element => {
        if(element == mx) mxcount++;
        if(element == mn) mncount++;
    });
    print(a.length - mncount - mncount);
}

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
// const n = parseInt(input[0], 10);
let secondLine = input[1].split(' ');
const nums = secondLine.map((a) => parseInt(a, 10));

if (nums.length <= 2) {
  console.log(0);
}

let min = nums[0];
let max  = nums[0];
let cmin = 1;
let cmax = 1;
let result = 0;

for (let i=1; i< nums.length; i++) {
  const num = nums[i];
  const nmin = Math.min(min, num);
  if (nmin !== min && min !== max) {
    result += cmin;
    cmin = 1;
  }
  if (num === min) {
    cmin += 1;
  }
  const nmax = Math.max(max, num);
  if (nmax !== max && min !== max) {
    result += cmax;
    cmax = 1;
  }
  if (num === max) {
    cmax += 1;
  }
  if (nmin === min && nmax === max && nmax !== num && nmin !== num) {
    result += 1;
  }
// console.log({num ,min, nmin, max, nmax, result});
  min = nmin;
  max = nmax;
}
console.log(result);
});

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
// const n = parseInt(input[0], 10);
let secondLine = input[1].split(' ');
const nums = secondLine.map((a) => parseInt(a, 10));

if (nums.length <= 2) {
  return 0;
}

let min = nums[0];
let max  = nums[0];
let cmin = 1;
let cmax = 1;
let result = 0;

for (let i=1; i< nums.length; i++) {
  const num = nums[i];
  const nmin = Math.min(min, num);
  if (nmin !== min && min !== max) {
    result += cmin;
    cmin = 1;
  }
  if (num === min) {
    cmin += 1;
  }
  const nmax = Math.max(max, num);
  if (nmax !== max && min !== max) {
    result += cmax;
    cmax = 1;
  }
  if (num === max) {
    cmax += 1;
  }
  if (nmin === min && nmax === max && nmax !== num && nmin !== num) {
    result += 1;
  }
// console.log({num ,min, nmin, max, nmax, result});
  min = nmin;
  max = nmax;
}
return result;
});

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
// const n = parseInt(input[0], 10);
let secondLine = input[1].split(' ');
const nums = secondLine.map((a) => parseInt(a, 10));

if (nums.length <= 2) {
  console.log(0);
  return
}

let min = nums[0];
let max  = nums[0];
let cmin = 1;
let cmax = 1;
let result = 0;

for (let i=1; i< nums.length; i++) {
  const num = nums[i];
  const nmin = Math.min(min, num);
  if (nmin !== min && min !== max) {
    result += cmin;
    cmin = 1;
  }
  if (num === min) {
    cmin += 1;
  }
  const nmax = Math.max(max, num);
  if (nmax !== max && min !== max) {
    result += cmax;
    cmax = 1;
  }
  if (num === max) {
    cmax += 1;
  }
  if (nmin === min && nmax === max && nmax !== num && nmin !== num) {
    result += 1;
  }
// console.log({num ,min, nmin, max, nmax, result});
  min = nmin;
  max = nmax;
}
console.log(result);
});

function findMin(array){
    var mn = Infinity;
    for(var i=0;i<array.length;i++){
        mn=Math.min(array[i],mn)
    }
    return mn;
}

function findMax(array){
    var mx = -Infinity;
    for(var i=0;i<array.length;i++){
        mx=Math.max(array[i],mx);
    }
    return mx;
}

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));
var res=0;

var mn=findMin(input);
var mx=findMax(input);

for(var i=1;i<=n-2;i++){
    if(input[i]>mn && input[i]<mx){
        res++;
    }
}

print(res);

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));
var res=0;
input.sort((a,b)=>a-b);
for(var i=1;i<n-1;i++){

    if((input[i-1]<input[i]) && (input[i]<input[i+1])){

        res++;
    }
}

print(res);

var n = Number(readline()),
    stewards = readline().split(' ').map(Number).sort(),
    counter = 0;
for (var i = 1; i < stewards.length - 1; i++){
    var count = i,
        thereIsBefore = false,
        thereIsAfter = false;
    while(count > 0) {
        if(stewards[count - 1] < stewards[i]){
            thereIsBefore = true;
            break;
        }
        count--;
    }
    while(count < stewards.length - 1) {
        if(stewards[count + 1] > stewards[i]){
            thereIsAfter = true;
            break;
        }
        count++;
    }
    if(thereIsAfter && thereIsBefore)
        counter++;

}

print(counter);

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  stewardsStrength = stewardsStrength.sort((a, b) => a - b)

  var i = 1
  var count = 0
  while (i < numberOfSteward - 1) {
    if (stewardsStrength[i - 1] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[i + 1]) {
      count += 1
    }
    i++
  }

  print(count)

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  var weaker = Infinity
  var stronger = -Infinity
  for (var i = 0; i < numberOfSteward; i++) {
    weaker = Math.min(weaker, numberOfSteward[i])
    stronger = Math.max(stronger, numberOfSteward[i])
  }

  var count = 0
  for (var i = 0; i < numberOfSteward; i++) {
    if (stewardsStrength[0] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[stewardsStrength.length - 1]) {
      count += 1
    }
  }

  print(count)

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  var weaker = Infinity
  var stronger = -Infinity
  for (var i = 0; i < numberOfSteward; i++) {
    weaker = Math.min(weaker, numberOfSteward[i])
    stronger = Math.max(stronger, numberOfSteward[i])
  }

  var count = 0
  for (var i = 0; i < numberOfSteward; i++) {
    if (weaker < stewardsStrength[i] && stewardsStrength[i] < stronger) {
      count += 1
    }
  }

  print(count)

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  stewardsStrength = stewardsStrength.sort((a, b) => a - b)

  var i = 1
  var count = 0
  while (i < numberOfSteward - 1) {
    if (stewardsStrength[i - 1] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[i + 1]) {
      count += 1
      i += 3
    } else {
      i++
    }
  }

  print(count)

var stuartsCount = +readline(),
    stuartsRaits = readline().split(/\s+/),
    minRait = stuartsRaits[0],
    maxRait = stuartsRaits[0],
    result = 0;

stuartsRaits.forEach(function(rait){
    var tmpRait;

    if(rait > maxRait) {
        tmpRait = maxRait;
        maxRait = rait;
        checkNeedGuard(tmpRait);
        return;
    }

    if(rait < minRait) {
        tmpRait = minRait;
        minRait = rait;
        checkNeedGuard(tmpRait);
        return;
    }

    checkNeedGuard();
});

function checkNeedGuard(rait) {
     if(rait > minRait && rait < maxRait) result++;
}

print(result);

try {require("codeforces")} catch(e){console = {log: function(){}, error: function(){}}};

var count, max, min, stuarts;
readline();
stuarts = readline().split(" ").map(Number);
min = stuarts[0];
max = 0;
count = 0;
stuarts.forEach(function(num) {
    if (num < min) {
        min = num;
    }
    if (num > max) {
        return max = num;
    }
});
console.log("ssss");
stuarts.forEach(function(num) {
    if (num > min && num < max) {
        return count+2;
    }
});
write(count);

var n = parseInt(readline());
var total = readline().split(" ").map(Number).sort((a, b) => a - b);

var se = new Set(total);

if (se.size <= 2) {
    print(0);
} else {
    print(se.size - 2);
}

var n = parseInt(readline());
var total = readline().split(" ").map(Number).sort((a, b) => a - b);

var count = total.length - 2;

for (var i = 0; i < total.length; i++) {
    if (total[i] === total[0] || total[i] === total[total.length - 1]) {
        count--;
    }
}

print(count < 0 ? 0: count);