You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.

For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.

NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 > 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 > 5$$$.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [len, x] = readLine().split(" ").map(Number);
    const arr1 = readLine().split(" ").map(Number);
    const arr2 = readLine().split(" ").map(Number);
    readLine();
    let flag = true;

    arr1.sort((a, b) => a - b);
    arr2.sort((a, b) => b - a);

    for (let i = 0; i < len; i++) {
      if (arr1[i] + arr2[i] > x) {
        console.log("No");
        flag = false;
        break;
      }
    }
    if (flag) console.log("Yes");
  }
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var N = one[0];
		var K = one[1];
		var alist = nextIntArray();
		alist.sort(function(a,b){
			return a - b;
		});
		var blist = nextIntArray();
		blist.sort(function(a,b){
			return b - a;
		});
		var isOK = true;
		for(var j = 0; j < N; j++){
			if(alist[j] + blist[j] > K){
				isOK = false;
			}
		}
		output[i] = (isOK) ? "YES" : "NO";
		if(i < t - 1){
			var sp = next();
		}
	}
	myout(myconv(output, 9));
}

let data = '';
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on('data', chunk => data += chunk);
process.stdin.on('end', () => {
  data = data.replace(/\s/g, ' ').replace(/  /g, ' ').split(' ').filter(x => !!x);
  main();
});
let __i = 0;

let read = () => Number(data[__i++]);
let readArray = (n) => { let t = new Array(n); for (let i = 0; i < n; i++) t[i] = Number(read()); return t; }

function main() {
  let t = read();
  while(t--) {
    let n = read(), x = read();
    let a = readArray(n);
    let b = readArray(n);

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

    let r = true;
    for (let i = 0; i < n; i++) {
      if (a[i] + b[i] > x) {
        r = false;
        break;
      }
    }
    console.log(r ? "Yes" : "No");
  }
}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let s=0;s<t;++s){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const s=n(r(747));let o="",i=[],u=0,l="";const a="local"===process.argv[2],h=t=>{if(a){if(i=s.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),s.default.writeFileSync("output.txt",l),console.log(l),s.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{i=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function p(){return i[u++]}function f(){return p().split(" ").map((t=>parseFloat(t)))}function c(){return p().split("")}e.default={runMain:h,runEachTest:t=>{h((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:p,nextNumbers:f,nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(f());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=f();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){a&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const s=n(r(312));s.default.runEachTest((function(){let[t,e]=s.default.nextNumbers(),r=s.default.nextNumbers(),n=s.default.nextNumbers();n.reverse();let o=r.filter(((t,r)=>t+n[r]<=e)).length==t;s.default.puts(o?"Yes":"No"),s.default.readline()}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var s=e[n]={exports:{}};return t[n].call(s.exports,s,s.exports,r),s.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n, x] = io.nextNumbers()
//   let a = io.nextNumbers()
//   let b = io.nextNumbers()
//
//   b.reverse()
//
//   let ok = a.filter((y, i) => y + b[i] <= x).length == n
//
//   io.puts(ok ? "Yes" : "No")
//
//   io.readline()
// }
//
// io.runEachTest(main)
// // io.runMain(main)

let input = ''

process.stdin.on('data', (x) => input += x)

process.stdin.on('end', () => {
  const lines = input.trim().split('\n').filter((line) => line.trim() !== '')
  const T = parseInt(lines[0])
  let curLine = 1
  for (let t = 0; t < T; t++) {
    const [n, x] = lines[curLine++].split(' ').map((k) => parseInt(k))
    const a = lines[curLine++].split(' ').map((k) => parseInt(k)).sort((u, v) => u - v)
    const b = lines[curLine++].split(' ').map((k) => parseInt(k)).sort((u, v) => v - u)
    let ans = 'Yes'
    for (let i = 0; i < n; i++) {
      if (a[i] + b[i] > x) {
        ans = 'No'
      }
    }
    console.log(ans)
  }
})

process.stdin.resume()
process.stdin.setEncoding('utf-8')
let stdInputString = ''

let currentLine = 0;

function readLine() {
    return stdInputString
}

process.stdin.once('data', rawData => {
    stdInputString += rawData
})

process.stdin.once('end', _ => {
    stdInputString = stdInputString
        .trim()
        .replace(/\r/g, '')
        .split('\n')
    main()
})

function main() {
    const w = readLine()
    let a = b = x = ''
    let ntest = w[0];

    for (let i = 0; i < ntest; i++) {
        w.map((ln, k) => {
            if ((4 * i) < k && k < (4 * (1 + i))) {
                if (k % 4 === 1)
                    x = ln.split(' ')[1]
                else if (k % 4 === 2)
                    a = ln.split(' ').map(Number)
                else
                    b = ln.split(' ').map(Number)
            }
        })

        function swap(index, b) {
            let len = b.length - 1;
            let tem = b[index]
            b[index] = b[len]
            b[len] = tem;
            return b;
        }

        function fulfills(b, a, sum) {
            if (a[a.length - 1] + b[b.length - 1] <= sum)
                return true
            else
                return false
        }

        function absoluteFalse(a, b, x) {
            if ((a[a.length - 1] >= x) || (b[b.length - 1] >= x)) {
                return true;
            } else if ((a[a.length - 1] + b[0]) > x) {
                return true;
            } else if ((b[b.length - 1] + a[0]) > x) {
                return true;
            } else if (a[a.length - 1] + b[0] === x) {
                b.splice(b.length, 0, b[0])
                b.shift()
                return b
            } else if ((a[a.length - 1] + b[0] <= x) && (a[a.length - 1] + b[1] > x)) {
                b.splice(b.length, 0, b[0])
                b.shift()
                return b
            } else
                return false
        }

        function preprocessing(a, b, x) {
            let abFalse = absoluteFalse(a, b, x)
            if (abFalse === true) {
                return false
            } else if (abFalse.length > 0) {
                return abFalse
            } else
                return true
        }

        function matchNsum(a, b, x, len) {
            let result = false;
            let op = ''
            if (preprocessing(a, b, x) === false)
                return false
            else if (preprocessing(a, b, x).length > 0)
                b = preprocessing(a, b, x)

            while (a.length > 0) {
                if (op === 'p') {
                    if (preprocessing(a, b, x) === false)
                        return false
                    else if (preprocessing(a, b, x).length > 0)
                        b = preprocessing(a, b, x)
                }

                if (fulfills(b, a, x)) {
                    result = true;
                    if (b.length > 0) {
                        b.pop();
                        a.pop();
                        op = 'p'
                        len = b.length
                    } else {
                        return result
                    }
                } else {
                    result = false;
                    if (len > 0) {
                        len--
                        b = swap(len, b)
                        op = 's'
                    } else if (a.length === 1) {
                        return result
                    }
                }
            }
            return result
        }
        result = matchNsum(a, b, x, b.length) === false ? 'No' : 'Yes'
        console.log(result)
        a = [];
        b = [];
    }
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')
let stdInputString = ''

let currentLine = 0;

function readLine() {
    return stdInputString
}

process.stdin.once('data', rawData => {
    stdInputString += rawData
})

process.stdin.once('end', _ => {
    stdInputString = stdInputString
        .trim()
        .replace(/\r/g, '')
        .split('\n')
    main()
})

function main() {
    const w = readLine()
    let a = b = x = ''
    let ntest = w[0];

    for (let i = 0; i < ntest; i++) {
        w.map((ln, k) => {
                if ((4 * i) < k && k < (4 * (1 + i))) {
                    if (k % 4 === 1) {
                        x = ln.split(' ')[1]
                            // console.log('len = ' + v[0])
                            // console.log('x = ' + x)
                    } else if (k % 4 === 2) {
                        a = ln.split(' ').map(Number)
                    } else {
                        b = ln.split(' ').map(Number)
                    }
                }
            })
            // Function:

        function swap(index, b) {
            let len = b.length - 1;
            let tem = b[index]
            b[index] = b[len]
            b[len] = tem;
            return b;
        }

        function fulfills(b, a, sum) {
            if (a[a.length - 1] + b[b.length - 1] <= sum)
                return true
            else
                return false
        }

        function absoluteFalse(a, b, x) {
            if ((a[a.length - 1] >= x) || (b[b.length - 1] >= x)) {
                return true;
            } else if ((a[a.length - 1] + b[0]) > x) {
                return true;
            } else if ((b[b.length - 1] + a[0]) > x) {
                return true;
            } else if (a[a.length - 1] + b[0] === x) {
                b.splice(b.length, 0, b[0])
                b.shift()
                return b
            } else if ((a[a.length - 1] + b[0] <= x) && (a[a.length - 1] + b[1] > x)) {
                b.splice(b.length, 0, b[0])
                b.shift()
                return b
            } else
                return false
        }

        function preprocessing(a, b, x) {
            let abFalse = absoluteFalse(a, b, x)
            if (abFalse === true) {
                a = []
                b = []
                return false
            } else if (abFalse.length > 0) {
                return abFalse
            } else
                return true
        }

        function matchNsum(a, b, x, len) {
            let result = false;
            let op = ''
            if (preprocessing(a, b, x) === false)
                return false
            else if (preprocessing(a, b, x).length > 0)
                b = preprocessing(a, b, x)

            while (a.length > 0) {
                if (op === 'p') {
                    if (preprocessing(a, b, x) === false)
                        return false
                    else if (preprocessing(a, b, x).length > 0)
                        b = preprocessing(a, b, x)
                }

                if (fulfills(b, a, x)) {
                    result = true;
                    if (b.length > 0) {
                        b.pop();
                        a.pop();
                        op = 'p'
                        len = b.length
                    } else {
                        return result
                    }
                } else {
                    result = false;
                    if (len > 0) {
                        len--
                        b = swap(len, b)
                        op = 's'
                    } else if (a.length === 1) {
                        return result
                    }
                }
            }
            return result
        }
        result = matchNsum(a, b, x, b.length) === false ? 'No' : 'Yes'
        console.log(result)
    }
}

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();
    });

    A();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function A(){
    let t = pi(readline());
    let y = t;
    while(t > 0){
        t--;
        if(t < y-1)
            readline();
        let [n,x] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let b = ti(readline().split(' '));

        let visited = new Array(n);
        visited.fill(false);
        let flag = true;

        for(let i = 0; i < n; i++){
            let max = a[i];
            let index = -1;
            for(let j = 0; j < n; j++){
                if(!visited[j] && a[i]+b[j] <= x){
                    max = Math.max(max, a[i]+b[j]);
                    index = j;
                }
            }
            if(index !== -1){
                visited[index] = true;
            }else{
                console.log('No');
                flag = false;
                break;
            }
        }
        if(flag)
            console.log('Yes');
    }
}

var N = Number(readline());

// 调整数组 a b 使得
// a[i] + b[i] <= x

for( ; N; N -- && readline())
{
	print(['No', 'Yes'][test() + 0]);
}

function test()
{
	var x = Number(readline().split(' ')[1]);
	var a = readline().split(' ').map(e => Number(e)).sort((a, b) => a - b);
	var b = readline().split(' ').map(e => Number(e)).sort((a, b) => b - a);

	for(var i = 0; i < a.length; i ++)
	{
		if(a[i] + b[i] > x)
			return false;
	}

	return true;
}

var t=readline();

for (k = 0; k< t; k++){
	if (k > 0){
		var empty = readline();
	}
	var nx = readline();
	var a = readline().split(" ");
	var b = readline().split(" ");
	var shi = false;
	var x = +nx.split(" ")[1];
	for (i = 0; i < a.length; i++){
		var toDelete = a.length - (i + 1);

		if ((+a[toDelete] + +b[i]) > x){
			shi = true;
		}

	}
	if (shi == true){
		print ("No");
	}
	else{
		print ("Yes");
	}
}

var inputs = parseInt(readline());

for(var i =0;i<inputs;i++)
{
	var params = readline().split(" ").map(x => parseInt(x));
	var a =  readline().split(" ").map(x => parseInt(x));
	var b =  readline().split(" ").map(x => parseInt(x));
	readline();
	b.reverse();
	var isPossible = true;
	var n = params[0];
	var x = params[1];
    for(var j=0;j< n; j++){
        if(a[j]+b[j]>x)
        {
             isPossible = false;
            break;

        }

    }
    if(isPossible)
    {
        print('Yes');
    }
    else
    {
        print('No');
    }
}

(function () {
    var t = +readline();
    var i = 0;
    while(i++ < t) {
        rearrangeArray();
        readline();
    }

    function rearrangeArray() {
        var nums = readline().split(' ').map(Number);
        var n = nums[0], x = nums[1];
        var a = readline().split(' ').map(Number);
        var b = readline().split(' ').map(Number);
        var available = b.sort((j,k) => k-j);
        outer: for(var j = 0; j < n; j++) {
            var curLength = available.length
            for(var k = 0; k < curLength; k++) {
                if(available[k] <= x - a[j]) {
                    available.splice(k, 1);
                    continue outer;
                }
            }
            if(available.length >= curLength) {
                print("No");
                return;
            }
        }
        print("Yes");
    }
})();

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [len, x] = readLine().split(" ").map(Number);
    const arr1 = readLine().split(" ").map(Number);
    const arr2 = readLine().split(" ").map(Number);
    readLine();

    const [min1, max1, min2, max2] = [Math.min(...arr1), Math.max(...arr1), Math.min(...arr2), Math.max(...arr2)];
    if (x < min1 || x < min2 || min1 + max2 > x || min2 + max1 > x) console.log("No");
    else console.log("Yes");
  }
}

let input = ''

process.stdin.on('data', (x) => input += x)

process.stdin.on('end', () => {
  const lines = input.trim().split('\n').filter((line) => line.trim() !== '')
  const T = parseInt(lines[0])
  let curLine = 1
  for (let t = 0; t < T; t++) {
    const [n, x] = lines[curLine++].split(' ').map((k) => parseInt(k))
    const a = lines[curLine++].split(' ').map((k) => parseInt(k)).sort()
    const b = lines[curLine++].split(' ').map((k) => parseInt(k)).sort((u, v) => v - u)
    let ans = 'Yes'
    for (let i = 0; i < n; i++) {
      if (a[i] + b[i] > x) {
        ans = 'No'
      }
    }
    console.log(ans)
  }
})

let input = ''

process.stdin.on('data', (x) => input += x)

process.stdin.on('end', () => {
  const lines = input.trim().split('\n').filter((line) => line.trim() !== '')
  const T = parseInt(lines[0])
  let curLine = 1
  for (let t = 0; t < T; t++) {
    const [n, x] = lines[curLine++].split(' ').map((x) => parseInt(x))
    const a = lines[curLine++].split(' ').map((x) => parseInt(x)).sort()
    const b = lines[curLine++].split(' ').map((x) => parseInt(x)).sort((u, v) => v - u)
    let ans = 'Yes'
    for (let i = 0; i < n; i++) {
      if (a[i] + b[i] > x) {
        ans = 'No'
      }
    }
    console.log(ans)
  }
})

var t=readline();

for (k = 0; k< t; k++){
	if (k > 0){
		var empty = readline();
	}
	var nx = readline();
	var a = readline().split(" ");
	var b = readline().split(" ");
	var shi = false;
	var x = nx.split(" ")[1];
	for (i = 0; i < a.length; i++){
		var toDelete = a.length - (i + 1);

		if ((a[toDelete] + b[i]) > x){
			shi = true;
		}

	}
	if (shi == true){
		print ("No");
	}
	else{
		print ("Yes");
	}
}

var inputs = parseInt(readline());

for(var i =0;i<inputs;i++)
{
	var params = readline().split(" ").map(x => parseInt(x));

	var a =  readline().split(" ").map(x => parseInt(x));
	var b =  readline().split(" ").map(x => parseInt(x));

	a.sort();
	b.sort();
	b.reverse();
	var isPossible = true;
	var n = params[0];
	var x = params[1];
    for(var j=0;j< n; j++){
        if(a[j]+b[j]<=x)
        {
            continue
        }
        else
        {
            isPossible = false;
            break;
        }
    }
    if(isPossible)
    {
        print('Yes');
    }
    else
    {
        print('No');
    }
}

var inputs = parseInt(readline());

for(var i =0;i<inputs;i++)
{
	var params = readline().split(" ").map(x => parseInt(x));
	var a =  readline().split(" ").map(x => parseInt(x));
	var b =  readline().split(" ").map(x => parseInt(x));
	readline();

	a.sort();
	b.sort();
	b.reverse();
	var isPossible = true;
	var n = params[0];
	var x = params[1];
    for(var j=0;j< n; j++){
        if(a[j]+b[j]<=x)
        {
            continue
        }
        else
        {
            isPossible = false;
            break;
        }
    }
    if(isPossible)
    {
        print('Yes');
    }
    else
    {
        print('No');
    }
}


Vasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi.Vasya wonders what the numbers ai could be like. Of all the possible options he likes the one sequence with the minimum possible last number an. Help Vasya restore the initial sequence.It is guaranteed that such a sequence always exists.

The first line contains a single integer number n (1 ≤ n ≤ 300). Next n lines contain integer numbers b1, ..., bn  — the required sums of digits. All bi belong to the range 1 ≤ bi ≤ 300.

Print n integer numbers, one per line — the correct option for numbers ai, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to bi.  If there are multiple sequences with least possible number an, print any of them. Print the numbers without leading zeroes.

(function() {
	var n = parseInt(readline());
	var a = [0];
	for (var i = 0; i < n; i++) {
		a[0]++;
		for (var j = 0; a[j] > 9; j++) {
			a[j] = 0;
			a[j + 1] = (a[j + 1] === undefined? 1 : a[j + 1] + 1);
		}
		var b = parseInt(readline());
		var ok = false;
		do {
//			print(a);
			var sum = b;
//			print(a);
//			for (var k = 0; k < 1000000000; k++) {
//				if (k == 777777) print("WAIT...");
//			}
			a.forEach(function(el) {
				sum -= el;
			});
			if (sum >= 0) {
				ok = true;
				a = a.map(function(el) {
					var dt = Math.min(sum, 9 - el);
					sum -= dt;
					return el + dt;
				});
				while (sum > 0) {
					dt = Math.min(sum, 9);
					sum -= dt;
					a.push(dt);
				}
			} else {
				if (b <= a[a.length - 1]) {
//					print("OK");
					a.push(0);
				}
				sum = 0;
				for (j = a.length - 1; j >= 0; j--) {
					sum += a[j];
					if (sum >= b) {
//						print("j = "+j+";");
						a[j + 1]++;
						var k = j + 1;
						while (a[k] > 9) {
							a[k] = 0;
							if (a[k + 1] === undefined) a.push(0);
							a[k + 1]++;
							k++;
						}
						k = j;
						do {
							a[k] = 0;
							k--;
						} while (k >= 0);
						break;
					}
				}
			}
		} while (!ok);
		var out = a.reverse();
		var outString = "";
		for (j = 0; j < out.length; j++) {
			outString += out[j];
		}
		print(outString);
		a.reverse();
	}
}());

(function() {
	var n = parseInt(readline());
	var a = [0];
	for (var i = 0; i < n; i++) {
		a[0]++;
		for (var j = 0; a[j] > 9; j++) {
			a[j] = 0;
			a[j + 1] = (a[j + 1] === undefined? 1 : a[j + 1] + 1);
		}
		var b = parseInt(readline());
		var ok = false;
		do {
//			print(a);
			var sum = b;
//			print(a);
//			for (var k = 0; k < 1000000000; k++) {
//				if (k == 777777) print("WAIT...");
//			}
			a.forEach(function(el) {
				sum -= el;
			});
			if (sum >= 0) {
				ok = true;
				a = a.map(function(el) {
					var dt = Math.min(sum, 9 - el);
					sum -= dt;
					return el + dt;
				});
				while (sum > 0) {
					dt = Math.min(sum, 9);
					sum -= dt;
					a.push(dt);
				}
			} else {
				if (b <= a[a.length - 1]) {
//					print("OK");
					a.push(0);
				}
				sum = 0;
				for (j = a.length - 1; j >= 0; j--) {
					sum += a[j];
					if (sum >= b) {
//						print("j = "+j+";");
						a[j + 1]++;
						var k = j + 1;
						while (a[j] > 9) {
							a[k] = 0;
							a[k + 1]++;
							k++;
						}
						k = j;
						do {
							a[k] = 0;
							k--;
						} while (k >= 0);
						break;
					}
				}
			}
		} while (!ok);
		var out = a.reverse();
		var outString = "";
		for (j = 0; j < out.length; j++) {
			outString += out[j];
		}
		print(outString);
		a.reverse();
	}
}());


Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of $$$n$$$ steps. At the $$$i$$$-th step, a place is chosen for the number $$$i$$$ $$$(1 \leq i \leq n)$$$. The position for the number $$$i$$$ is defined as follows:  For all $$$j$$$ from $$$1$$$ to $$$n$$$, we calculate $$$r_j$$$  — the minimum index such that $$$j \leq r_j \leq n$$$, and the position $$$r_j$$$ is not yet occupied in the permutation. If there are no such positions, then we assume that the value of $$$r_j$$$ is not defined.  For all $$$t$$$ from $$$1$$$ to $$$n$$$, we calculate $$$count_t$$$  — the number of positions $$$1 \leq j \leq n$$$ such that $$$r_j$$$ is defined and $$$r_j = t$$$.  Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the $$$count$$$ array is maximum.  The generator selects one of these positions for the number $$$i$$$. The generator can choose any position. Let's have a look at the operation of the algorithm in the following example:  Let $$$n = 5$$$ and the algorithm has already arranged the numbers $$$1, 2, 3$$$ in the permutation. Consider how the generator will choose a position for the number $$$4$$$:  The values of $$$r$$$ will be $$$r = [3, 3, 3, 4, \times]$$$, where $$$\times$$$ means an indefinite value.  Then the $$$count$$$ values will be $$$count = [0, 0, 3, 1, 0]$$$.  There are only two unoccupied positions in the permutation: $$$3$$$ and $$$4$$$. The value in the $$$count$$$ array for position $$$3$$$ is $$$3$$$, for position $$$4$$$ it is $$$1$$$.  The maximum value is reached only for position $$$3$$$, so the algorithm will uniquely select this position for number $$$4$$$. Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind $$$p_1, p_2, \ldots, p_n$$$ and decided to find out if it could be obtained as a result of the generator.Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^5)$$$  — the number of test cases. Then the descriptions of the test cases follow. The first line of the test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — the size of the permutation. The second line of the test case contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$)  — the permutation written by Denis. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

Print "Yes" if this permutation could be obtained as a result of the generator. Otherwise, print "No". All letters can be displayed in any case.

NoteLet's simulate the operation of the generator in the first test.At the $$$1$$$ step, $$$r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]$$$. The maximum value is reached in any free position, so the generator can choose a random position from $$$1$$$ to $$$5$$$. In our example, it chose $$$5$$$.At the $$$2$$$ step, $$$r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]$$$. The maximum value is reached in positions from $$$1$$$ to $$$4$$$, so the generator can choose a random position among them. In our example, it chose $$$1$$$.At the $$$3$$$ step, $$$r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]$$$. The maximum value is $$$2$$$ and is reached only at the $$$2$$$ position, so the generator will choose this position.At the $$$4$$$ step, $$$r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]$$$. The maximum value is $$$3$$$ and is reached only at the $$$3$$$ position, so the generator will choose this position.At the $$$5$$$ step, $$$r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]$$$. The maximum value is $$$4$$$ and is reached only at the $$$4$$$ position, so the generator will choose this position.In total, we got a permutation of $$$2, 3, 4, 5, 1$$$, that is, a generator could generate it.

// Lang: Node.js
'use strict';
let x = '', y = 0;
let print = x => console.log(x);

process.stdin.on('data', inputStdin => x += inputStdin);
process.stdin.on('end', () => { x = x.split('\n'); main(); });
let readline = () => x[y++];

// ************************ Code Start ***************************

function main() {

 var Tc = parseInt(readline());
 while (Tc--) {
   var n = parseInt(readline());
   var ar = readline().split(' ').map((x) => parseInt(x));
   var ok = 1;
   for (var i = 1; i < n; i++) {
     if (ar[i] > ar[i - 1] && ar[i] != ar[i - 1] + 1) {
       ok = 0;
       break;
     }
   }
   print(ok ? 'YES' : 'NO');
 }
}

'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 main() {
    let range = readline();
    for(let r=0;r<range;r++) {
        let data = readline()
        let a = readline().split(" ").map(x => parseInt(x));

        if(data === 1) {
            console.log("Yes");
            break;
        }

        let output = "Yes";

        for(let i=1;i<data - 1;i++) {
            if(a[i] - a[i - 1] > 1) {
                output = "No";
                break;
            }
        }

        console.log(output);
    }

}

'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 main() {
    let range = readline();
    for(let r=0;r<range;r++) {
        let data = readline()
        let a = readline().split(" ").map(x => parseInt(x));

        if(data === 1) {
            console.log("Yes")
        } else if(a[a.length - 1] - a[0] < 1) {
            console.log("Yes")
        } else {
            console.log("No");
        }

    }

}


Let's denote a $$$k$$$-step ladder as the following structure: exactly $$$k + 2$$$ wooden planks, of which  two planks of length at least $$$k+1$$$ — the base of the ladder;  $$$k$$$ planks of length at least $$$1$$$ — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders $$$1$$$ and $$$3$$$ are correct $$$2$$$-step ladders and ladder $$$2$$$ is a correct $$$1$$$-step ladder. On the first picture the lengths of planks are $$$[3, 3]$$$ for the base and $$$[1]$$$ for the step. On the second picture lengths are $$$[3, 3]$$$ for the base and $$$[2]$$$ for the step. On the third picture lengths are $$$[3, 4]$$$ for the base and $$$[2, 3]$$$ for the steps.   You have $$$n$$$ planks. The length of the $$$i$$$-th planks is $$$a_i$$$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.The question is: what is the maximum number $$$k$$$ such that you can choose some subset of the given planks and assemble a $$$k$$$-step ladder using them?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The queries are independent. Each query consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of planks you have. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the lengths of the corresponding planks. It's guaranteed that the total number of planks from all queries doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per query. The $$$i$$$-th integer is the maximum number $$$k$$$, such that you can choose some subset of the planks given in the $$$i$$$-th query and assemble a $$$k$$$-step ladder using them. Print $$$0$$$ if you can't make even $$$1$$$-step ladder from the given set of planks.

NoteExamples for the queries $$$1-3$$$ are shown at the image in the legend section.The Russian meme to express the quality of the ladders:

t=+readline()

function cmp(a,b)
{
    if (+a<+b)
    return 1
    if (+a==+b)
    return 0
    if (+a>+b)
    return -1
}

function min(a,b)
{
    if (a<b)
    return a
    return b
}

while(t--)
{
    n=+readline()
    a=readline().split(' ').map(function(x){return +x})
    a.sort(cmp)
    x1=0
    if (n<=2||a[1]==1)
    {
        print(0)
    } else {
        print(min(n-2,a[1]-1))
    }
}

const readLines = () => {
	try {
		return require("fs").readFileSync("input.txt", "utf8").split(/[\r\n]+/);
	} catch(e) {}
	const lines = [];
	for(var line; undefined !== (line = readline()); )
		lines.push(line);
	return lines;
};
const output = (text) => {
	try {
		console.log(text);
	} catch(e) {}
	try {
		text.toString().split(/[\r\n]+/).map(s => print(s));
	} catch(e) {}
};

var a = readLines();
var count = +a.shift();
var result = [];
for(var i = 0; i < count; i++) {
	var numBoards = +a.shift();
	var boards = a.shift().split(" ").map(Number);;
	boards.sort((l, r) => r - l);
	result.push( Math.min((boards[1]|0) - 1, numBoards - 2) );
}

output( result.join("\n") );

var t = +readline()

for ( var i = 0 ; i < t ; i++ ) {
  var n = +readline()
  var planks = readline().split(' ')
  planks.sort((a,b) => a - b)

  var l = Math.min(planks.pop(), planks.pop()) - 1
  print(Math.min(l, planks.length))
}

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {
    var T = +rd();
    while (T-->0) {
        var n = +rd();
        var A = rdAr().sortGt();
        var max2 = A[1] - 1;
        pr(Math.min(max2, n - 2));
    }
};

if (INPUT) {
INPUT = INPUT.split('\n').reverse();
readline = () => INPUT.pop();
write = (s) => {OUTPUT += s};
print = (s) => {OUTPUT += s + '\n'};
}
const rd = readline;
const wr = write;
const pr = print;
const rdAr = () => rd().split(' ').map(v => +v);
const prAr = (a) => pr(a.join(' '));
const cmpLt = (a, b) => a - b;
const cmpGt = (a, b) => b - a;
Array.prototype.sortLt = function() { return this.sort(cmpLt); };
Array.prototype.sortGt = function() { return this.sort(cmpGt); };
const crAr = function(length, ...fillArgs) { return new Array(length).fill(...fillArgs); };
const getPrimes = function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(var i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;};

try {main();}finally{return OUTPUT;}
})();

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        let longItems = data.reduce((agr, item) => {
            item = +item;
            if (item > agr[0]) agr.unshift(item);
            else if (item > agr[1]) agr[1] = item;
            return agr;
        }, [0, 0]);
        let maxKForLong = longItems[1] - 1;
        let maxKForShort = data.length - 2;
        let k = Math.min(maxKForLong, maxKForShort);
        return k > 0 ? k : 0;

    }

    let testCount = 1;

    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ");
        console.log(foo(data));
        testCount++;
    }
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        let longItems = data.reduce((agr, item) => {
            item = +item;
            if (item > agr[0]) agr.unshift(item);
            else if (item > agr[1]) agr[1] = item;
            return [agr[0], agr[1]];
        }, [0, 0]);
        let maxKForLong = longItems[1] - 1;
        //console.log("maxKForLong", maxKForLong);
        let maxKForShort = data.length - 2;
        //console.log("maxKForShort", maxKForShort);
        let k = Math.min(maxKForLong, maxKForShort);
        return k > 0 ? k : 0;

    }

    let testCount = 1;

    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ");
        //console.log(data)
        console.log(foo(data));
        testCount++;
    }
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        let longItems = data.reduce((agr, item) => {
            if (item > agr[0]) agr.unshift(item);
            else if (item > agr[1]) agr[1] = item;
            return [agr[0], agr[1]];
        }, [0, 0]);
        let maxKForLong = longItems[1] - 1;
        //console.log("maxKForLong", maxKForLong);
        let maxKForShort = data.length - 2;
        //console.log("maxKForShort", maxKForShort);
        let k = Math.min(maxKForLong, maxKForShort);
        return k > 0 ? k : 0;

    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ").map(Number);
        //console.log(data)
        answer += foo(data) + "\n";
        testCount++;
    }
    console.log(answer)
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data, min, max) {
	    function check(data, k) {
	        //console.log("k ", k);
	        let lengthLong = data.reduce((agr, value) => {
	            if (value >= k + 1) agr++;
	            return agr;
	        }, 0);

	        //console.log("lengthLong", lengthLong);
	        let hasLong = lengthLong >=2 ;

	        let hasShort = (data.length - 2) >= k;
	        return hasLong && hasShort;
	    }

	    let middle = min + Math.ceil((max - min) / 2);
	    //console.log(min, max, middle);
	    let isValid = check(data, middle);
	    let isNextValid = check(data, middle + 1);
	    //console.log(isValid, isNextValid);
	    if (isValid && !isNextValid) return middle;
	    if (max <= min) return 0;

	    if (isValid && isNextValid) {
	        min = middle;
	    } else {
	        max = (max !== middle) ? middle : middle -1;
	    }
	    return foo(data, min, max);
	}

	let testCount = 1;

	while(testCount <= +lines[0]) {
	    let data = lines[testCount * 2].split(" ");
	    //console.log("data ", data);
	    console.log(foo(data, 1, data.length - 2));
	    testCount++;
	}
})

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;
  }

  if (c % 2) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => b - a);

  const max = arr[1];

  console.log(Math.min(max - 1, arr.length - 2));

  // let ans = 0;

  // for (let i = 2; i < arr.length; i++) {
  //   ans++;
  // }

  // console.log(Math.min(max - 1, ans));

  c++;
});

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;
  }

  if (c % 2) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => b - a);

  const max = arr[1];
  let ans = 0;

  for (let i = 2; i < arr.length; i++) {
    ans++;
  }

  console.log(Math.min(max - 1, ans));

  c++;
});

const readLines = () => {
	try {
		return require("fs").readFileSync("input.txt", "utf8").split(/[\r\n]+/);
	} catch(e) {}
	const lines = [];
	for(var line; undefined !== (line = readline()); )
		lines.push(line);
	return lines;
};
const output = (text) => {
	try {
		console.log(text);
	} catch(e) {}
	try {
		text.toString().split(/[\r\n]+/).map(s => print(s));
	} catch(e) {}
};

var a = readLines();
var count = +a.shift();
var result = [];
for(var i = 0; i < count; i++) {
	var numBoards = +a.shift();
	var boards = a.shift().split(" ").map(Number);;
	boards.sort((l, r) => r - l);
	result.push( Math.max((boards[1]|0) - 1, numBoards - 2) );
}

output( result.join("\n") );

const readLines = () => {
	const lines = [];
	for(var line; undefined !== (line = readline()); )
		lines.push(line);
	return lines;
};
const output = (text) => {
	text.toString().split(/[\r\n]+/).map(s => print(s));
};
//const input = readline;
/**/

const a = readLines();
const count = +a.shift();
var result = [];
for(var i = 0; i < count; i++) {
	const numBoards = +a.shift();
	const boards = a.shift().split(" ").map(Number);
	boards.sort((l, r) => r - l);
	result.push( Math.max((boards[1]|0) - 1, numBoards - 2) );
}

output( result.join("\n") );

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        let longItems = data.reduce((agr, item) => {
            if (item > agr[0]) agr.unshift(item);
            else if (item > agr[1]) agr[1] = item;
            return agr;
        }, [0, 0]);
        let maxKForLong = longItems[1] - 1;
        let maxKForShort = data.length - 2;
        let k = Math.min(maxKForLong, maxKForShort);
        return k > 0 ? k : 0;

    }

    let testCount = 1;

    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ");
        console.log(foo(data));
        testCount++;
    }
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        let longItems = data.reduce((agr, item) => {
            item = +item;
            if (item > agr[0]) agr.unshift(item);
            else if (item > agr[1]) agr[1] = item;
            return agr;
        }, [0, 0]);
        let maxKForLong = longItems[1] - 1;
        console.log("maxKForLong",maxKForLong);
        let maxKForShort = data.length - 2;
        console.log("maxKForShort",maxKForShort);
        let k = Math.min(maxKForLong, maxKForShort);
        return k > 0 ? k : 0;

    }

    let testCount = 1;

    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ");
        console.log(data)
        console.log(foo(data));
        testCount++;
    }
})

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;
  }

  if (c % 2) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => b - a);

  const max = arr[1];
  let ans = 0;

  for (let i = 2; i < arr.length; i++) {
    if (arr[i] < max) {
      ans++;
    }
  }

  console.log(Math.min(max - 1, ans));

  c++;
});

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;
  }

  if (c % 2) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => b - a);

  const max = arr[1];
  let ans = 0;

  for (let i = 2; i < arr.length; i++) {
    if (arr[i] < max) {
      ans++;
    }
  }

  console.log(ans);

  c++;
});


Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.

The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish.

Print a single integer — the minimum number of times Valera will need to wash a plate/bowl.

NoteIn the first sample Valera will wash a bowl only on the third day, so the answer is one.In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once.In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl.

var l=readline().split(' ');
var n=+l[0];
var m=+l[1];
var k=+l[2];

var ans=0;
readline().split(' ').forEach(function(v){
	if(v==='1'){
		if(m>0){
			m--;
		}else{
			ans++;
		}
	}else{
		if(k>0){
			k--;
		}else if(m>0){
			m--;
		}else{
			ans++;
		}
	}
});
print(ans);

var input = readline().split(" ").map(Number), n = +input[0], m = +input[1], k = +input[2],
a = readline().split(" ");
var cnt = 0;

a.forEach(function(day){
	if(day == "1"){
		if(m > 0){
			m--;
		}
		else{
			cnt++;
		}
	}
	else{
		if(k > 0){
			k--;
		}
		else{
			if(m > 0){
				m--;
			}
			else{
				cnt++;
			}
		}
	}
});

write(cnt);

var n = readline().split(' ');
var m = +n[1];
var l = +n[2];
n = +n[0];

var x = 0;
var a = readline().split(' ').map(function (e) {
	switch (e) {
		case '1':
			if (m > 0) m--;
			else x++;
			break;

		case '2':
			if (l > 0) l--;
			else {
				if (m > 0) m--;
				else x++;
			}
			break;
	}
});

print(x);

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]);
	};
	return tokens;
}

function main() {
	var integers = tokenizeIntegers(readline());
	var numDays = integers[0], bowlCap = integers[1], dishCap = integers[2];

	var meals = tokenizeIntegers(readline());
	var typeCounts = { 1: 0, 2: 0 };
	for (var i = 0; i < meals.length; i += 1) {
		typeCounts[meals[i]] += 1;
	}

	var bowls = bowlCap - typeCounts[1];
	if (bowls > 0) {
		dishCap += bowls;
	}
	var dishes = dishCap - typeCounts[2];

	var result = -(Math.min(bowls, 0) + Math.min(dishes, 0));
	print(result);
}

main();

// 369A     Валера и тарелки

// var n = parseInt(readline());

var input_line = readline().split(' ').map(Number);

var n = input_line[0];
var m = input_line[1];
var r = input_line[2];

var arr = readline().split(' ').map(Number);

var out = 0;
var count1 = 0;
var count2 = 0;

arr.forEach(function(item, i, arr) {
    if (item == 1) {
        count1 ++;
    } else {
        count2 ++;
    };
});

if (count1 > m) {
    out += (count1 - m);
} else {
    r += (m - count1);
};

if (r < count2) {
    out += count2 - r;
};

print(out);

function main(){
    var nmk  = readline().split(' ');
    var washTime = 0;
    var b = parseInt(nmk[1]), p = parseInt(nmk[2]);
    readline().split(' ').forEach(function (i){
        if ( i === "1" ){
            if ( b > 0 ){
                --b;
            }else{
                ++washTime;
            }
        }else{
            if ( p > 0 ){
                --p;
            }else if ( b > 0 ){
                --b;
            }else{
                ++washTime;
            }
        }
    });
    print(washTime);
}
main();

var n = readline().split(' ');
var m = +n[1];
var l = +n[2];
n = +n[0];

var x = 0;
var a = readline().split(' ').map(function (e) {
	switch (e) {
		case '1':
			if (m > 0) m--;
			else x++;
			break;

		case '2':
			if (l > 0) l--;
			else x++;
			break;
	}
});

print(x);

var n = readline().split(' ');
var m = +n[1];
var l = +n[2];
n = +n[0];

var x = 0;
var a = readline().split(' ').map(function (e) {
	switch (e) {
		case '1':
			if (m > 0) m--;
			else x++;
			break;

		case '2':
			if (m > 0) m--;
			else {
				if (l > 0) l--;
				else x++;
			}
			break;
	}
});

print(x);

// 369A     Валера и тарелки

// var n = parseInt(readline());

var input_line = readline().split(' ').map(Number);

var n = input_line[0];
var m = input_line[1];
var r = input_line[2];

var arr = readline().split(' ').map(Number);

var out = 0;
var count1 = 0;
var count2 = 0;

arr.forEach(function(item, i, arr) {
    if (item == 1) {
        count1 ++;
    } else {
        count2 ++;
    };
});

if (count1 > m) {
    out += (count1 - m);
} else {
    count2 += (m - count1);
};

if (count2 < (n - count1)) {
    out += (n - count1) - count2;
};

print(out);

// 369A     Валера и тарелки

// var n = parseInt(readline());

var input_line = readline().split(' ').map(Number);

var n = input_line[0];
var m = input_line[1];
var r = input_line[2];

var arr = readline().split(' ').map(Number);

var out = 0;
var count1 = 0;
var count2 = 0;

arr.forEach(function(item, i, arr) {
    if (item = 1) {
        count1 ++;
    } else {
        count2 ++;
    };
});

if (count1 > m) {
    out += (count1 - m);
} else {
    count2 += (m - count1);
};

if (count2 < (n - count1)) {
    out += (n - count1) - count2;
};

print(out);

function main(){
    var nmk  = readline().split(' ');
    var plan = readline().split(' ');
    var i, washTime = 0;
    var b = parseInt(nmk[1]), p = parseInt(nmk[2]);
    for( i = 0 ; i < nmk[0] ; ++i ){
        if ( plan[i] == 1 ){
            if ( b == 0 ){
                b = parseInt(nmk[1]), p = parseInt(nmk[2]);
                ++washTime;
            }
            --b;
        }else{
            if ( p > 0 ){
                --p;
            }else if ( b > 0 ){
                --b;
            }else{
                b = parseInt(nmk[1]), p = parseInt(nmk[2]);
                ++washTime;
                --p;
            }
        }
    }
    print(washTime);
}
main();


Berland shop sells $$$n$$$ kinds of juices. Each juice has its price $$$c_i$$$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of juices. Each of the next $$$n$$$ lines contains an integer $$$c_i$$$ $$$(1 \le c_i \le 100\,000)$$$ and a string $$$s_i$$$ — the price of the $$$i$$$-th juice and the vitamins it contains. String $$$s_i$$$ contains from $$$1$$$ to $$$3$$$ characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string $$$s_i$$$. The order of letters in strings $$$s_i$$$ is arbitrary.

Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.

NoteIn the first example Petya buys the first, the second and the fourth juice. He spends $$$5 + 6 + 4 = 15$$$ and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is $$$16$$$, which isn't optimal.In the second example Petya can't obtain all three vitamins, as no juice contains vitamin "C".

function find(str,vitamin){
    for (var j = 0;j<str.length;j++){
        if (str.charAt(j) === vitamin) return true;
    }
    return false;
}
var A =Number.MAX_VALUE, B =Number.MAX_VALUE, C =Number.MAX_VALUE, AB =Number.MAX_VALUE, AC =Number.MAX_VALUE, BC =Number.MAX_VALUE, ABC = Number.MAX_VALUE;
var n = +readline();
while (n-->0){
    var ip = readline().split(' ');
    if (find(ip[1],'A')){
        A = Math.min(A,ip[0]);
    }
    if (find(ip[1],'B')){
        B = Math.min(B,ip[0]);
    }
    if (find(ip[1],'C')){
        C = Math.min(C,ip[0]);
    }
    if (ip[1] === 'AB' || ip[1] === 'BA'){
        AB = Math.min(ip[0],AB);
    }
    if (ip[1] === 'AC' || ip[1] === 'CA'){
        AC = Math.min(ip[0],AC);
    }
    if (ip[1] === 'CB' || ip[1] === 'BC'){
        BC = Math.min(ip[0],BC);
    }

    if (ip[1].length === 3){
        ABC = Math.min(ip[0],ABC);
    }
    AB = Math.min(A+B,AB);
    AC = Math.min(A+C,AC);
    BC = Math.min(B+C,BC);
    ABC = Math.min(A+B+C,AB+C,AC+B,BC+A,ABC);
}
print((ABC === Number.MAX_VALUE)?-1:ABC);

dp = new Array(8);
for (i=1;i<8;i++){
    dp[i] = Number.MAX_VALUE;
}
dp[0] = 0;
n = +readline();
while (n-->0){
    ip = readline().split(' ');
    value = +ip[0];
    plus = 0;
    ip[1].split('').forEach(x => {
        plus |= 1<<(x.charCodeAt() - 65);
    });
    for (i = 7;i>=0;i--){
        dp[i | plus] = Math.min(dp[i | plus], dp[i]+value);
    }
}
print(dp[7] === Number.MAX_VALUE?-1:dp[7]);

function find(str,vitamin){
    for (var j = 0;j<str.length;j++){
        if (str.charAt(j) === vitamin) return true;
    }
    return false;
}
var A =Number.MAX_VALUE, B =Number.MAX_VALUE, C =Number.MAX_VALUE, AB =Number.MAX_VALUE, AC =Number.MAX_VALUE, BC =Number.MAX_VALUE, ABC = Number.MAX_VALUE;
var n = +readline();
while (n-->0){
    var ip = readline().split(' ');
    if (ip[1] === 'A'){
        A = Math.min(A,ip[0]);
    }
    if (ip[1] === 'B'){
        B = Math.min(B,ip[0]);
    }
    if (ip[1] === 'C'){
        C = Math.min(C,ip[0]);
    }
    if (ip[1] === 'AB' || ip[1] === 'BA'){
        AB = Math.min(ip[0],AB);
    }
    if (ip[1] === 'AC' || ip[1] === 'CA'){
        AC = Math.min(ip[0],AC);
    }
    if (ip[1] === 'CB' || ip[1] === 'BC'){
        BC = Math.min(ip[0],BC);
    }

    if (ip[1].length === 3){
        ABC = Math.min(ip[0],ABC);
    }
    AB = Math.min(A+B,AB);
    AC = Math.min(A+C,AC);
    BC = Math.min(B+C,BC);
    ABC = Math.min(A+B+C,AB+C,AC+B,BC+A,ABC,AB+AC,AB+BC,BC+AC);
}
print((ABC === Number.MAX_VALUE)?-1:ABC);

var n = Number(readline());
var input = [];
var hash = {}; var key;
var keymap = {A : "001",
  B : "010" ,
  C : "100",
  AB : "011",
  BC: "110",
  AC: "101",
  ABC: "111"};

for(var i=0; i<n; i++) {
    var juices = readline().split(' ');
    var key = keymap[juices[1].split('').sort().join('')];
    if (hash[key] == undefined) {
      hash[key] = Number(juices[0]);
    } else {
      hash[key] = Math.min(hash[key], Number(juices[0]));
    }
}

var min = hash["111"] ? hash["111"] : -1;

if(hash["001"] && hash["010"] && hash["100"]) {
  min = (min == -1) ? hash["001"]+hash["010"]+hash["100"] : Math.min(min, hash["001"]+hash["010"]+hash["100"]);
}
for(i in hash) {
    for(var j in hash) {
      if((i|j) == "111" && i != j) {
        min = (min == -1) ? (hash[i]+hash[j]) : Math.min(min, hash[i]+hash[j]);
      }
    }
}

print(min);

// var lineIdx = 0;
// var readline = () => {
//   var input = ["4", "5 C", "6 B", "16 ACB", "4 A"]
//   return input[lineIdx++];
// };
// var print = (str) => {
//   console.log(str);
// };

var min = (...arg) => {
  var min;
  for(var a of arg){
    if(a != NaN && (!min || a < min)){
      min = a;
    }
  }
  return min;
}

var res = new Array(8)
var n = parseInt(readline())
for(var i = 0; i < n; i++){
  var line = readline().split(" ");
  var price = parseInt(line[0]);
  var bit = line[1].split('').sort().join('');
  if(!res[bit] || res[bit] > price){
    res[bit] = price;
  }
}

var minPrice = min(res['A'] + res['B'] + res['C'],
res['A'] + res['BC'],
res['B'] + res['AC'],
res['C'] + res['AB'],
res['AB'] + res['AC'],
res['AB'] + res['BC'],
res['BC'] + res['AC'],
res['ABC'])
print(minPrice || -1)

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: parseInt(inp[0]),
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
                break;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1];
                break;
            }
        }

        updateSum();

    }

    if (sortedArr['ABC'] && sum > sortedArr['ABC']) {
        sum = sortedArr['ABC'];
    }

    //console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 198,
//     vit: 'BC'
// }, {
//     cost: 259,
//     vit: 'AC'
// }, {
//     cost: 125,
//     vit: 'BA'
// }, {
//     cost: 298,
//     vit: 'CAB'
// }, {
//     cost: 252,
//     vit: 'CA'
// }, {
//     cost: 98,
//     vit: 'AC'
// }, {
//     cost: 284,
//     vit: 'BAC'
// }])

function find(str,vitamin){
    for (var j = 0;j<str.length;j++){
        if (str.charAt(j) === vitamin) return true;
    }
    return false;
}
var A =Number.MAX_VALUE, B =Number.MAX_VALUE, C =Number.MAX_VALUE, AB =Number.MAX_VALUE, AC =Number.MAX_VALUE, BC =Number.MAX_VALUE, ABC = Number.MAX_VALUE;
var n = +readline();
while (n-->0){
    var ip = readline().split(' ');
    if (ip[1] === 'A'){
        A = Math.min(A,ip[0]);
    }
    if (ip[1] === 'B'){
        B = Math.min(B,ip[0]);
    }
    if (ip[1] === 'C'){
        C = Math.min(C,ip[0]);
    }
    if (ip[1] === 'AB' || ip[1] === 'BA'){
        AB = Math.min(ip[0],AB);
    }
    if (ip[1] === 'AC' || ip[1] === 'CA'){
        AC = Math.min(ip[0],AC);
    }
    if (ip[1] === 'CB' || ip[1] === 'BC'){
        BC = Math.min(ip[0],BC);
    }

    if (ip[1].length === 3){
        ABC = Math.min(ip[0],ABC);
    }
    AB = Math.min(A+B,AB);
    AC = Math.min(A+C,AC);
    BC = Math.min(B+C,BC);
    ABC = Math.min(A+B+C,AB+C,AC+B,BC+A,ABC);
}
print((ABC === Number.MAX_VALUE)?-1:ABC);

var n = Number(readline());
var input = [];
var hash = {}; var key;
var keymap = {A : 001,
  B : 010 ,
  C : 100,
  AB : 011,
  BC: 110,
  AC: 101,
  ABC: 111};

for(var i=0; i<n; i++) {
    var juices = readline().split(' ');
    var key = keymap[juices[1].split('').sort().join('')];
    if (hash[key] == undefined) {
      hash[key] = Number(juices[0]);
    } else {
      hash[key] = Math.min(hash[key], Number(juices[0]));
    }
}

var min = -1;
if(hash["001"] && hash["010"] && hash["100"]) {
  min = hash["001"]+hash["010"]+hash["100"];
}
for(i in hash) {
    for(var j in hash) {
      if((i|j) == "111" && i != j) {
        min = (min == -1) ? (hash[i]+hash[j]) : Math.min(min, hash[i]+hash[j]);
      }
    }
}

print(min);

var n = Number(readline());
var input = [];
var hash = {}; var key;
var keymap = {A : "001",
  B : "010" ,
  C : "100",
  AB : "011",
  BC: "110",
  AC: "101",
  ABC: "111"};

for(var i=0; i<n; i++) {
    var juices = readline().split(' ');
    var key = keymap[juices[1].split('').sort().join('')];
    if (hash[key] == undefined) {
      hash[key] = Number(juices[0]);
    } else {
      hash[key] = Math.min(hash[key], Number(juices[0]));
    }
}

var min = -1;
if(hash["001"] && hash["010"] && hash["100"]) {
  min = hash["001"]+hash["010"]+hash["100"];
}
for(i in hash) {
    for(var j in hash) {
      if((i|j) == "111" && i != j) {
        min = (min == -1) ? (hash[i]+hash[j]) : Math.min(min, hash[i]+hash[j]);
      }
    }
}

print(min);

var n = Number(readline());
var input = [];
var hash = {}; var key;
var keymap = {A : "001",
  B : "010" ,
  C : "100",
  AB : "011",
  BC: "110",
  AC: "101",
  ABC: "111"};

for(var i=0; i<n; i++) {
    var juices = readline().split(' ');
    var key = keymap[juices[1].split('').sort().join('')];
    if (hash[key] == undefined) {
      hash[key] = Number(juices[0]);
    } else {
      hash[key] = Math.min(hash[key], Number(juices[0]));
    }
}

var min = -1;
if(hash["001"] && hash["010"] && hash["100"]) {
  min = hash["001"]+hash["010"]+hash["100"];
}
for(i in hash) {
    for(var j in hash) {
      if((i|j) == "111" && i != j) {
        min = (min == -1) ? (hash[i]+hash[j]) : Math.min(min, hash[i]+hash[j]);
      }
    }
}

if (hash["111"] && hash["111"] < min) {
  min = hash["111"];
}

print(min);

// var lineIdx = 0;
// var readline = () => {
//   var input = ["4", "5 C", "6 B", "16 ACB", "4 A"]
//   return input[lineIdx++];
// };
// var print = (str) => {
//   console.log(str);
// };

var min = (...arg) => {
  var min;
  for(var a of arg){
    if(a != NaN && (!min || a < min)){
      min = a;
    }
  }
  return min;
}

var bitStr = (val) => {
  var res = 0;
  for(var c of val){
    if(c == 'A'){
      res = res | 1;
    } else if(c == 'B'){
      res = res | 2;
    } else {
      res = res | 4;
    }
  }
  return res;
}

var res = new Array(8)
var n = parseInt(readline())
for(var i = 0; i < n; i++){
  var line = readline().split(" ");
  var price = parseInt(line[0]);
  var bit = bitStr(line[1]);
  if(!res[bit] || res[bit] > price){
    res[bit] = price;
  }
}

var minPrice = min(res[1] + res[2] + res[4], res[1] + res[6], res[2] + res[5], res[3] + res[4], res[7])
print(minPrice || -1)

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: inp[0],
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    print(inArr)
    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    // sortedArr = {}
    // costSorted.forEach((value) => {
    //     sortedArr[value[0]] = value[1];
    // })

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1]
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //  console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 100,
//     vit: 'A'
// }, {
//     cost: 355,
//     vit: 'BCA'
// }, {
//     cost: 150,
//     vit: 'BC'
// }, {
//     cost: 160,
//     vit: 'AC'
// }, {
//     cost: 180,
//     vit: 'B'
// }, {
//     cost: 190,
//     vit: 'CA'
// }])

// foo([{
//     cost: 10,
//     vit: 'AB'
// }, {
//     cost: 15,
//     vit: 'BA'
// }])

// foo([{
//     cost: 5,
//     vit: 'BA'
// }, {
//     cost: 11,
//     vit: 'CB'
// }])

// foo([{
//     cost: 5,
//     vit: 'C'
// }, {
//     cost: 6,
//     vit: 'B'
// }, {
//     cost: 16,
//     vit: 'BAC'
// }, {
//     cost: 4,
//     vit: 'A'
// }])

var number = readline();
var input = []
print(input)
for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    print(inp)
    input.push({
        cost: inp[0],
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    // sortedArr = {}
    // costSorted.forEach((value) => {
    //     sortedArr[value[0]] = value[1];
    // })

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1]
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //  console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 100,
//     vit: 'A'
// }, {
//     cost: 355,
//     vit: 'BCA'
// }, {
//     cost: 150,
//     vit: 'BC'
// }, {
//     cost: 160,
//     vit: 'AC'
// }, {
//     cost: 180,
//     vit: 'B'
// }, {
//     cost: 190,
//     vit: 'CA'
// }])

// foo([{
//     cost: 10,
//     vit: 'AB'
// }, {
//     cost: 15,
//     vit: 'BA'
// }])

// foo([{
//     cost: 5,
//     vit: 'BA'
// }, {
//     cost: 11,
//     vit: 'CB'
// }])

// foo([{
//     cost: 5,
//     vit: 'C'
// }, {
//     cost: 6,
//     vit: 'B'
// }, {
//     cost: 16,
//     vit: 'BAC'
// }, {
//     cost: 4,
//     vit: 'A'
// }])

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: parseInt(inp[0]),
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
                break;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1 && data[0] != 'ABC') {
                misVitSum += data[1];
                break;
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 198,
//     vit: 'BC'
// }, {
//     cost: 259,
//     vit: 'AC'
// }, {
//     cost: 125,
//     vit: 'BA'
// }, {
//     cost: 298,
//     vit: 'CAB'
// }, {
//     cost: 252,
//     vit: 'CA'
// }, {
//     cost: 98,
//     vit: 'AC'
// }, {
//     cost: 284,
//     vit: 'BAC'
// }])

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: parseInt(inp[0]),
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    // sortedArr = {}
    // costSorted.forEach((value) => {
    //     sortedArr[value[0]] = value[1];
    // })

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
                break;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1]
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 9,
//     vit: 'C'
// }, {
//     cost: 3,
//     vit: 'B'
// }])

// foo([{
//     cost: 100,
//     vit: 'A'
// }, {
//     cost: 355,
//     vit: 'BCA'
// }, {
//     cost: 150,
//     vit: 'BC'
// }, {
//     cost: 160,
//     vit: 'AC'
// }, {
//     cost: 180,
//     vit: 'B'
// }, {
//     cost: 190,
//     vit: 'CA'
// }])

// foo([{
//     cost: 10,
//     vit: 'AB'
// }, {
//     cost: 15,
//     vit: 'BA'
// }])

// foo([{
//     cost: 5,
//     vit: 'BA'
// }, {
//     cost: 11,
//     vit: 'CB'
// }])

// foo([{
//     cost: 5,
//     vit: 'C'
// }, {
//     cost: 6,
//     vit: 'B'
// }, {
//     cost: 16,
//     vit: 'BAC'
// }, {
//     cost: 4,
//     vit: 'A'
// }])

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: parseInt(inp[0]),
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
                break;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1];
                break;
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 198,
//     vit: 'BC'
// }, {
//     cost: 259,
//     vit: 'AC'
// }, {
//     cost: 125,
//     vit: 'BA'
// }, {
//     cost: 298,
//     vit: 'CAB'
// }, {
//     cost: 252,
//     vit: 'CA'
// }, {
//     cost: 98,
//     vit: 'AC'
// }, {
//     cost: 284,
//     vit: 'BAC'
// }])

var number = readline();
var input = []

for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: parseInt(inp[0]),
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    // sortedArr = {}
    // costSorted.forEach((value) => {
    //     sortedArr[value[0]] = value[1];
    // })

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1]
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //  console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 100,
//     vit: 'A'
// }, {
//     cost: 355,
//     vit: 'BCA'
// }, {
//     cost: 150,
//     vit: 'BC'
// }, {
//     cost: 160,
//     vit: 'AC'
// }, {
//     cost: 180,
//     vit: 'B'
// }, {
//     cost: 190,
//     vit: 'CA'
// }])

// foo([{
//     cost: 10,
//     vit: 'AB'
// }, {
//     cost: 15,
//     vit: 'BA'
// }])

// foo([{
//     cost: 5,
//     vit: 'BA'
// }, {
//     cost: 11,
//     vit: 'CB'
// }])

// foo([{
//     cost: 5,
//     vit: 'C'
// }, {
//     cost: 6,
//     vit: 'B'
// }, {
//     cost: 16,
//     vit: 'BAC'
// }, {
//     cost: 4,
//     vit: 'A'
// }])

var number = readline();
var input = []
for (var i = 0; i < number; i++) {
    var inp = readline().split(' ');
    input.push({
        cost: inp[0],
        vit: inp[1]
    })
}

if (!Object.entries)
    Object.entries = function (obj) {
        var ownProps = Object.keys(obj),
            i = ownProps.length,
            resArray = new Array(i); // preallocate the Array

        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];
        return resArray;
    };

function foo(inArr) {

    var sum = -1;
    var sortedArr = {}
    for (var data of inArr) {
        data.vit = data.vit.split('').sort().join('');
        if (!sortedArr[data.vit] || sortedArr[data.vit] > data.cost) {
            sortedArr[data.vit] = data.cost;
        }
    }

    // sortedArr = {}
    // costSorted.forEach((value) => {
    //     sortedArr[value[0]] = value[1];
    // })

    for (var vit in sortedArr) {
        var missingVit = 'ABC'.replace(vit, '').split('');
        var tempSum = sortedArr[vit];
        var misVitSum = 0;

        var updateSum = function () {
            if (misVitSum) {
                tempSum += misVitSum;
                if (sum > tempSum || sum == -1) {
                    sum = tempSum
                }
            }

        }
        //is single aviable
        for (var missVit of missingVit) {
            if (sortedArr[missVit]) {
                misVitSum += sortedArr[missVit]
            }
            else {
                misVitSum = 0;
            }
        }

        updateSum();

        //check combination
        misVitSum = 0;
        missingVit = missingVit.join('');
        var costSorted = Object.entries(sortedArr).sort((a, b) => a[1] - b[1]);
        for (var data of costSorted) {
            if (data[0].indexOf(missingVit) != -1) {
                misVitSum += data[1]
            }
        }

        updateSum();

        //check abc
        misVitSum = 0;
        if (sortedArr['ABC']) {
            misVitSum += sortedArr['ABC'];
        }
        updateSum();

    }

    //  console.log(sum);
    print(sum)
}

foo(input)

// foo([{
//     cost: 100,
//     vit: 'A'
// }, {
//     cost: 355,
//     vit: 'BCA'
// }, {
//     cost: 150,
//     vit: 'BC'
// }, {
//     cost: 160,
//     vit: 'AC'
// }, {
//     cost: 180,
//     vit: 'B'
// }, {
//     cost: 190,
//     vit: 'CA'
// }])

// foo([{
//     cost: 10,
//     vit: 'AB'
// }, {
//     cost: 15,
//     vit: 'BA'
// }])

// foo([{
//     cost: 5,
//     vit: 'BA'
// }, {
//     cost: 11,
//     vit: 'CB'
// }])

// foo([{
//     cost: 5,
//     vit: 'C'
// }, {
//     cost: 6,
//     vit: 'B'
// }, {
//     cost: 16,
//     vit: 'BAC'
// }, {
//     cost: 4,
//     vit: 'A'
// }])


You are beta testing the new secret Terraria update. This update will add quests to the game!Simply, the world map can be represented as an array of length $$$n$$$, where the $$$i$$$-th column of the world has height $$$a_i$$$.There are $$$m$$$ quests you have to test. The $$$j$$$-th of them is represented by two integers $$$s_j$$$ and $$$t_j$$$. In this quest, you have to go from the column $$$s_j$$$ to the column $$$t_j$$$. At the start of the quest, you are appearing at the column $$$s_j$$$.In one move, you can go from the column $$$x$$$ to the column $$$x-1$$$ or to the column $$$x+1$$$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $$$p$$$ to the column with the height $$$q$$$, then you get some amount of fall damage. If the height $$$p$$$ is greater than the height $$$q$$$, you get $$$p - q$$$ fall damage, otherwise you fly up and get $$$0$$$ damage.For each of the given quests, determine the minimum amount of fall damage you can get during this quest.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5; 1 \le m \le 10^5$$$) — the number of columns in the world and the number of quests you have to test, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the height of the $$$i$$$-th column of the world. The next $$$m$$$ lines describe quests. The $$$j$$$-th of them contains two integers $$$s_j$$$ and $$$t_j$$$ ($$$1 \le s_j, t_j \le n; s_j \ne t_j$$$), which means you have to move from the column $$$s_j$$$ to the column $$$t_j$$$ during the $$$j$$$-th quest. Note that $$$s_j$$$ can be greater than $$$t_j$$$.

Print $$$m$$$ integers. The $$$j$$$-th of them should be the minimum amount of fall damage you can get during the $$$j$$$-th quest completion.

'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 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++) {

        output(result);
    }*/
    let [n, m] = readline().split(' ').map(Number);
    let arr = readline().split(' ').map(Number);

    let prefix = new Array(n).fill(0);
    for (let i = 1; i < n; i++) {
        let cost = arr[i - 1] > arr[i] ? arr[i - 1] - arr[i] : 0;
        prefix[i] = prefix[i - 1] + cost;
    }

    let suffix = new Array(n).fill(0);
    for (let i = n - 2; i >= 0; i--) {
        let cost = arr[i + 1] > arr[i] ? arr[i + 1] - arr[i] : 0;
        suffix[i] = suffix[i + 1] + cost;
    }

    for (let test = 0; test < m; test++) {
        let [s, t] = readline().split(' ').map(Number).map(x => x - 1);

        let result = 0;
        if (s > t) {
            result = suffix[t] - suffix[s];
        } else {
            result = prefix[t] - prefix[s];
        }
        output(result);
    }
}

'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 main(){
    var tests = 1;
    for (let t = 0;t < tests; ++t) {
        var nq = readline().split(' ').map((x)=>parseInt(x));
        var arr = readline().split(' ').map((x) => parseInt(x));
        var pref = Array(nq[0]+1).fill(0);
        var suff = Array(nq[0]+1).fill(0);
        let  n = nq[0];
        // console.log(arr);

        for (let i = 1;i < nq[0];++i) {
            if (arr[i] < arr[i-1]) {
                pref[i+1] = arr[i-1] - arr[i];
            }
            if (arr[n-1-i] < arr[n-i]) {
                suff[n-i] = arr[n-i] - arr[n-1-i];
            }
            pref[i+1] = pref[i+1] + pref[i];
            suff[n-i] = suff[n+1-i] + suff[n-i];
        }
        // console.log(pref);
        // console.log(suff);

        for (let i = 0;i < nq[1];++i) {
            var st = readline().split(' ').map((x)=>parseInt(x));
            if (st[0] < st[1]) {
                console.log(pref[st[1]] - pref[st[0]]);
            } else {
                console.log(suff[st[1]] - suff[st[0]]);

            }
            // console.log(st);
        }
    }

}

'use strict';

function solve(n, m, a, b) {
  const l = new Array(n),
        r = new Array(n);
  for (let i = 0; i < n; i++) {
    var _l, _a;
    l[i] = ((_l = l[i - 1]) !== null && _l !== void 0 ? _l : 0) + Math.max(0, ((_a = a[i - 1]) !== null && _a !== void 0 ? _a : a[i]) - a[i]);
  }
  for (let i = n - 1; i >= 0; i--) {
    var _r, _a2;
    r[i] = ((_r = r[i + 1]) !== null && _r !== void 0 ? _r : 0) + Math.max(0, ((_a2 = a[i + 1]) !== null && _a2 !== void 0 ? _a2 : a[i]) - a[i]);
  }
  const res = new Array(m);
  for (let i = 0; i < m; i++) {
    const [x, y] = b[i].map(num => num - 1);
    if (x === y) res[i] = 0;else if (x < y) {
      res[i] = l[y] - l[x];
    } else {
      res[i] = r[y] - r[x];
    }
  }
  return res.join('\n');
}

async function main(read) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      const b = [];
      let tmp = m;
      while (tmp--) {
        b.push((await read()).split(' ').map(Number));
      }
      res[i] = solve(n, m, a, b);
    }
    return 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', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});


Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence $$$s$$$ is called correct if:   $$$s$$$ is empty;  $$$s$$$ is equal to "($$$t$$$)", where $$$t$$$ is correct bracket sequence;  $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.

First of line of input contains a single number $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — length of the sequence which Petya received for his birthday. Second line of the input contains bracket sequence of length $$$n$$$, containing symbols "(" and ")".

Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No".

NoteIn the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence.In the second example, there is no way to move at most one bracket so that the sequence becomes correct.In the third example, the sequence is already correct and there's no need to move brackets.

const n = Number(readline());
print((s => {
  var count = 0;
  var mismatch = false;
  for (var c of s)
    if (c === "(") count++;
    else if (count) count--;
    else {
      if (mismatch) return false;
      else mismatch = true;
    }
  return count === (mismatch ? 1 : 0);
})(readline().substring(0, n)) ? "Yes" : "No");