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

function hotelier(s) {
  const arr = [];
  arr.length = 10;
  arr.fill(0);

  let lp = 0;
  let rp = arr.length - 1;

  for (let i = 0; i < s.length; i++) {
    if (s[i] === 'L') {
      arr[lp] = 1;
    } else if (s[i] === 'R') {
      arr[rp] = 1;
    }
    while (arr[lp] === 1) {
      lp++;
    }
    while (arr[rp] === 1) {
      rp--;
    }

    if (!isNaN(parseInt(s[i], 10))) {
      const evictedRoomIndex = parseInt(s[i], 10);
      arr[evictedRoomIndex] = 0;
      if (lp > evictedRoomIndex) {
        lp = evictedRoomIndex;
      }
      if (rp < evictedRoomIndex) {
        rp = evictedRoomIndex;
      }
    }
  }
  return arr.join('');
}

const n = Number(readline())
const actions = readline()
const result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Array.from(actions).forEach((el, i) => {
    if(el === 'L') {
        setRoom(result, 'L')
    } else if(el === 'R') {
        setRoom(result, 'R')
    } else {
        result[el] = 0
    }
})

function setRoom(arr, c) {
    if(c === 'R') arr.reverse()
    for(var i = 0; i < arr.length; i++) {
        if(arr[i] == 0) {
            arr[i] = 1
            break
        }
    }
    if(c === 'R') arr.reverse()
}
print(result.join(""))

// const io = require('../lol-io.js');
// const readline = io.readline;
// const print = io.print;

var n = Number(readline());
var memory = readline();
var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

for(var i = 0; i < n; ++i) {
    if (memory[i] === 'L') {
        for (var j = 0; j < result.length; ++j) {
            if (!result[j]) {
                result[j] = 1;
                break;
            }
        }
    } else if (memory[i] === 'R') {
        for (var j = result.length - 1; j >= 0; --j) {
            if (!result[j]) {
                result[j] = 1;
                break;
            }
        }
    } else {
        result[memory[i]] = 0;
    }
}

print(result.join(''));

'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 n = parseInt(readline());
    let s = readline();

    let arr = new Array(10);

    for (let i = 0; i < arr.length; i++) {
        arr[i] = 0;
    }

    let k = 0;

    for (let i = 0; i < n; i++) {
        if (s[i] === 'R') {
            k = arr.lastIndexOf(0);
        } else if (s[i] === 'L') {
            k = arr.indexOf(0);
        } else {
            arr[parseInt(s[i])] = 0;
            continue;
        }

        arr[k] = 1;
    }

    console.log(arr.join(''));
}

'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 count = readline();
    let events = readline();
    const rooms  = Array(10).fill(0);

    for(let i=0;i<count;i++){
        if(events[i]==="L"){
           for(let i=0;i<rooms.length;i++){
                if(rooms[i]===0){
                    rooms[i]=1;
                    break;
                }
            }
        } else if(events[i]==="R"){
              for(let i=rooms.length-1;i>=0;i--){
                    if(rooms[i]===0){
                        rooms[i]=1;
                        break;
                    }
                }
        } else{
           rooms[events[i]]=0;
        }
    }
    console.log(rooms.join(""));
}

const n = Number(readline());
const actions = readline();

const rooms = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

[...actions].forEach(action => {
  if (action === 'L') {
    for (var i = 0; i < 10; i++) {
      if (rooms[i] === 0) {
        rooms[i] = 1;
        break;
      }
    }
  } else if (action === 'R') {
    for (i = 9; i > -1; i--) {
      if (rooms[i] === 0) {
        rooms[i] = 1;
        break;
      }
    }
  } else {
    rooms[Number(action)] = 0;
  }
});

print(rooms.join(''));

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

var main = function() {"use strict";
    // TODO
    var n = rdN();
    var s = rdS();
    var A = crAr(10, 0);
    for (var i = 0 ; i < s.length; ++i) {
        var ch = s[i];
        //pr(ch)
        if (ch === 'L') {
            var j = 0;
            while (A[j]) {
                ++j;
            }
            A[j] = 1;
        } else if (ch === 'R') {
            var j = 9;
            while (A[j]) {
                --j;
            }
            A[j] = 1;
        } else {
            A[+ch] = 0;
        }
    }
    wr(A.join(''));
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();

const processData = (lines) => {
  const [count, sequence] = lines
  const rooms = '0000000000'.split('')
  const setClosest = (isLeft) => {
    if (isLeft) {
      for (let j = 0; j < rooms.length; j++) {
        if (rooms[j] === '0') {
          rooms[j] = '1'
          return
        }
      }
    } else {
      for (let j = rooms.length - 1; j >= 0; j--) {
        if (rooms[j] === '0') {
          rooms[j] = '1'
          return
        }
      }
    }
  }

  for (let i = 0; i < Number(count); i++) {
    const action = sequence[i]
    switch (action) {
      case 'L':
        setClosest(true)
        break;
      case 'R':
        setClosest(false)
        break;
      default:
        rooms[Number(action)] = '0'
    }
  }
  console.log(rooms.join(''))
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const { EOL } = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

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

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

  const rooms = new Array(10).fill(0);

  for (let i = 0; i < str.length; i++) {
    if (str[i] === 'L') {
      const idx = rooms.indexOf(0);
      rooms[idx] = 1;
    }
    else if (str[i] === 'R') {
      const idx = rooms.lastIndexOf(0);
      rooms[idx] = 1;
    }
    else {
      rooms[str[i]] = 0;
    }
  }

  console.log(rooms.join(''));
  c++;
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
function main() {
    let count = readline();
    let events = readline();
    const rooms  = Array(10).fill(0);

    for(let i=0;i<count;i++){
        if(events[i]==="L"){
           for(let i=0;i<rooms.length;i++){
                if(rooms[i]===0){
                    rooms[i]=1;
                    break;
                }
            }
        } else if(events[i]==="R"){
              for(let i=rooms.length;i>0;i--){
                    if(rooms[i]===0){
                        rooms[i]=1;
                        break;
                    }
                }
        } else{
           rooms[events[i]]=0;
        }
    }
    console.log(rooms);
}

'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 count = readline();
    let events = readline();
    const rooms  = Array(10).fill(0);

    for(let i=0;i<count;i++){
        if(events[i]==="L"){
           for(let i=0;i<rooms.length;i++){
                if(rooms[i]===0){
                    rooms[i]=1;
                    break;
                }
            }
        } else if(events[i]==="R"){
              for(let i=rooms.length;i>0;i--){
                    if(rooms[i]===0){
                        rooms[i]=1;
                        break;
                    }
                }
        } else{
           rooms[events[i]]=0;
        }
    }
    console.log(rooms.join(""));
}

'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 count = readline();
    let events = readline();
    const rooms  = Array(10).fill(0);

    for(let i=0;i<count;i++){
        if(events[i]==="L"){
           for(let i=0;i<rooms.length;i++){
                if(rooms[i]===0){
                    rooms[i]=1;
                    break;
                }
            }
        } else if(events[i]==="R"){
              for(let i=rooms.length-1;i>0;i--){
                    if(rooms[i]===0){
                        rooms[i]=1;
                        break;
                    }
                }
        } else{
           rooms[events[i]]=0;
        }
    }
    console.log(rooms.join(""));
}

const processData = (lines) => {
  const [count, sequence] = lines
  const rooms = '0000000000'
  const setClosest = (rooms, isLeft) => {
    if (isLeft) {
      for (let j = 0; j < rooms.length; j++) {
        if (rooms[j] === '0') {
          rooms[j] = '1'
          return rooms
        }
      }
    } else {
      for (let j = rooms.length - 1; j >= 0; j--) {
        if (rooms[j] === '0') {
          rooms[j] = '1'
          return rooms
        }
      }

    }
  }

  for (let i = 0; i < count; i++) {
    const action = sequence[i]
    switch (action) {
      case 'L':
        setClosest(rooms, true)
        break
      case 'R':
        setClosest(rooms, true)
        break
      default:
        rooms[action] = '0'

    }
    console.log(rooms)
  }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const { EOL } = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

const processData = (lines) => {
  const [count, sequence] = lines
  const rooms = '0000000000'
  const setClosest = (isLeft) => {
    if (isLeft) {
      for (let j = 0; j < rooms.length; j++) {
        if (rooms[j] === '0') {
          rooms[j] = '1'
          return rooms
        }
      }
    } else {
      for (let j = rooms.length - 1; j >= 0; j--) {
        if (rooms[j] === '0') {
          rooms[j] = '1'
          return rooms
        }
      }

    }
  }

  for (let i = 0; i < count; i++) {
    const action = sequence[i]
    switch (action) {
      case 'L':
        setClosest(true)
        break
      case 'R':
        setClosest(true)
        break
      default:
        rooms[action] = '0'

    }
  }
  console.log(rooms)

}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const { EOL } = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

const processData = (lines) => {
  const [count, sequence] = lines
  const rooms = '0000000000'
  const setClosest = (isLeft) => {
    if (isLeft) {
      for (let j = 0; j < rooms.length; j++) {
        if (rooms[j] === '0') {
          rooms[j] = '1'
          return
        }
      }
    } else {
      for (let j = rooms.length - 1; j >= 0; j--) {
        if (rooms[j] === '0') {
          rooms[j] = '1'
          return
        }
      }
    }
  }

  for (let i = 0; i < count; i++) {
    const action = sequence[i]
    switch (action) {
      case 'L':
        setClosest(true)
        break;
      case 'R':
        setClosest(true)
        break;
      default:
        rooms[Number(action)] = '0'
    }
  }
  console.log(rooms)

}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const { EOL } = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})


var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const [a, b, k] = rna();
		const al = rna();
		const bl = rna();

		const bm = new Map();
		const gm = new Map();
		for (let i = 0; i < k; i++) {
			bm.set(al[i], bm.has(al[i]) ? bm.get(al[i]) + 1 : 1);
			gm.set(bl[i], gm.has(bl[i]) ? gm.get(bl[i]) + 1 : 1);

		}

		let ans = 0;
		for (let i = 0; i < k; i++) {
			ans += k - bm.get(al[i]) - gm.get(bl[i]) + 1;
		}
		ans /= 2;

		console.log(ans);
	}
}

'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++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var xx = 0
        var answer = []
        var [a, b, k] = readline().split(' ').map((x, i) => {
            return Number(x)
        });
        var aaa = []
        var aa = readline().split(' ').map((x, i) => {
            return Number(x)
        });
        var bbb = []

        var bb = readline().split(' ').map((x, i) => {
            answer.push([aa[i], Number(x)])
            return Number(x)
        })
        var result = 0
        var count = 0
        var ii = 0
        var a1 = 0
        var b1 = 0
        // console.log(aaa)
        // console.log(bbb)
        answer.map((x, i) => {
            a1 = aaa[answer[i][0]] ? aaa[answer[i][0]] : 0
            b1 = bbb[answer[i][1]] ? bbb[answer[i][1]] : 0
            // console.log(i, a1, b1, i+1-a1 - b1)
            count = i-a1 - b1
            aaa[answer[i][0]] = a1 + 1
            bbb[answer[i][1]] = b1 + 1

            result+= count > 0 ? count : 0
        })
        console.log(result)
    })
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var A = nextInt();
		var B = nextInt();
		var K = nextInt();
		var list = new Array(A + B);
		for(var j = 0; j < A + B; j++){
			list[j] = {
				child : new Set()
			};
		}
		var L = nextIntArray(K);
		var R = nextIntArray(K);
		for(var j = 0; j < K; j++){
			list[L[j] - 1].child.add(A + R[j] - 1);
			list[A + R[j] - 1].child.add(L[j] - 1);
		}
		var Edge = K;
		var output = 0;
		for(var j = 0; j < K; j++){
			output += Edge - (list[L[j] - 1].child.size + list[A + R[j] - 1].child.size - 1);
			Edge--;
			list[L[j] - 1].child.delete(A + R[j] - 1);
			list[A + R[j] - 1].child.delete(L[j] - 1);
		}
		myout(output);
	}
}


var str1 = readline();
var str2 = readline();
var op = readline().split(' ').map(Number);

var len1 = str1.length;
var len2 = str2.length;

var l = 0;
var r = len1;

var flags = [];

var test = function(x) {
  flags = [];
  var c = 0;
  for(var i = 0; i < x; i += 1) {
    flags[op[i] - 1] = true;
  }
  for(var i = 0; i < len1; i += 1) {
    if(!flags[i]) {
      c += (str2[c] === str1[i]) ? 1 : 0;
    }
  }
  return c >= len2;
}

while(l <= r) {
  var m = Math.floor((l + r) / 2);
  if(test(m)) {
    l = m + 1;
  } else {
    r = m - 1;
  }
}

print(l - 1);

Str1 = readline();
Str2 = readline();
Forbid = Array(Str1.length);
Pos = readline().split(' ').map(Number).map(x => x-1);
var l = 0,r = Str1.length;
var mid;
while(l < r) {
	mid = Math.ceil((l+r)/2);
	for(var i = 0;i < Str1.length;i++) {
		Forbid[i] = 0;
	}
	for(var i = 0;i<mid;i++) {
		Forbid[Pos[i]] = 1;
	}
	if(((ju,mStr1,mStr2,mForbid) => {
		//print(mForbid);
		var a=0,b=0;
		while(a < mStr1.length && b < mStr2.length) {
			while(a < mStr1.length && mForbid[a]==1)
				a++;
			if(a == mStr1.length)
				break;
			if(mStr1[a] == mStr2[b])  {
				b++;
				//print(a,b);
			}
			a++;
		}
		if(b==mStr2.length)
			return true;
		return false;
	})(mid,Str1,Str2,Forbid)) {
		l = mid;
	}
	else r = mid-1;
	//print(l,r);
}
print(l);


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

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

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

// ********** Code Start **********
function main() {
  var num = parseInt(readline())
	while(num--){
  var a = parseInt(readline())
  var line = readline().split(' ').map(Number)
  line.sort((a,b) => (a - b))
  var arr = line[0]
  var pre = 0
  for(let i = 0; i < line.length;i++){
    line[i]-= pre
    arr = (Math.max(arr, line[i]))
    pre += line[i]
  }
  print(arr)

}
}

'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 t = Number(readline())
    for (let j = 1; j <= t; j++) {
        let n=Number(readline());
        let a = readline().split(' ').map(Number)
        a.sort((a, b) => a - b)
        let ans=a[0],pre=0;
        for(let i=0;i<n;i++)
        {
            a[i]-=pre;
            ans=Math.max(ans,a[i]);
            pre+=a[i];
        }
        console.log(ans);
    }
}

const solve = (n,arr)=>{
     if(n===1){
          console.log(arr[0]);
          return;
     }
     arr.sort((a,b)=>a-b);
     let max = arr[0];
     for(let i=1;i<n;i++){
          let t  = arr[i] - arr[i-1];
          if(t>max) max = t;
     }
     console.log(max);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n  = parseInt(readline());
       let arr =  readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(n,arr);
  }
}
main();

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

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

// ********** Code Start **********
function main() {
  let num = parseInt(readline());
  while (num--) {
    let a = parseInt(readline());
    let line = readline().split(" ").map(Number);
    line.sort((a, b) => a - b);
    let arr = line[0];
    let pre = 0;
    for (let i = 0; i < line.length; i++) {
      line[i] -= pre;
      arr = Math.max(arr, line[i]);
      pre += line[i];
    }
    print(arr);
  }
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const INF = 1e9;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		a.sort((x, y) => x - y);

		let ans = -INF;
		a.unshift(0);
		for (let i = 1; i <= n; i++) {
			ans = Math.max(ans, a[i] - a[i-1]);
		}

		console.log(ans);
	}
}

process.stdin.setEncoding('utf-8')
const readline = require('readline')

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

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data * 2
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function solve([n], arr) {
    if (n === 1) {
        console.log(arr[0])
        return
    }
    arr.sort((a, b) => a - b)
    let max = 0
    for (let i = 0; i < n - 1; i++) {
        if (max < arr[i + 1] - arr[i]) {
            max = arr[i + 1] - arr[i]
        }
    }
    console.log((arr[0] < max) ? max : arr[0])
}

function main() {
    for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function gcd(a, b) {
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
// let a=readline().split(' ').map(Number)
// a.sort((a,b)=>a-b)

function main() {
    let t = Number(readline())
    for (let j = 1; j <= t; j++) {
        let n=Number(readline());
        let a = readline().split(' ').map(Number)
        a.sort((a, b) => a - b)
        let ans=a[0],pre=0;
        for(let i=0;i<n;i++)
        {
            a[i]-=pre;
            ans=Math.max(ans,a[i]);
            pre+=a[i];
        }
        console.log(ans);
    }
}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

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

// ********** Code Start **********
function main() {
  var num = parseInt(readline())
	while(num--){
  var a = parseInt(readline())
  var line = readline().split(' ').map(Number)
  line.sort((a,b) => (a - b))
  var set = new Set()
  var arr = []
  for(let i = 0;i < line.length;i++){
    set.add(line[i])
  }
  if(set.size == 1){
    print(line[0])
  }
  else{
    var t = line.length
    for(let i = 0; i < t;i++){
      arr.push(line[0])
      line.shift()
      for(let j = 0; j < line.length;j++){
        line[j] -= arr[i]
      }
    }
    print(Math.max(...arr))
  }
}
}

'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 t = Number(readline())
    for (let j = 1; j <= t; j++) {
        let [x,n]=readline().split(' ').map(Number);
        if(n==0)
        {
            console.log(x);
            continue;
        }
        let i = 1;
        let ans=0;
        if(n%4==1)
            ans=-n;
        else if(n%4==2)
            ans=1;
        else if(n%4==3)
            ans=n+1;
        if(Math.abs(x)%2==1)
            ans=-ans;
        console.log(ans+x);
    }
}


"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const bs = (n, val) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    let to = (mid * (mid + 1n)) / 2n;
    if (to === val) return mid;
    else if (to < val) low = mid + 1n;
    else {
      ans = mid;
      high = mid - 1n;
    }
  }
  return ans;
};
const bs1 = (n, val) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    let to = (n * (n + 1n)) / 2n - (mid * (mid - 1n)) / 2n;
    if (to === val) return n - mid + 1n;
    else if (to < val) high = mid - 1n;
    else {
      ans = n - mid + 1n;
      low = mid + 1n;
    }
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, x] = BInpArr();
    let total = n * (n + 1n) - n;
    if (x >= total) console.log(2n * n - 1n + "");
    else {
      let to = (n * (n + 1n)) / 2n;
      if (x < to) {
        console.log(bs(n, x) + "");
      } else if (x > to) {
        console.log(n + bs1(n - 1n, x - to) + "");
      } else console.log(n + "");
    }
  }
};
solve();

'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 foo(x) {

    console.log(x);
}

function find_count(K,y){
 if(y<=K){
  return y*(y+1n)/2n;
 }
 else{
  return find_count(K,K)*2n-K-find_count(K,2n*K-1n-y);
 }
}

function lower_bound(K, x){
  let low=0n;
  let high=2n*K-1n;
  while(low<high){

    let mid = (high+low)/2n
    if(find_count(K,mid)<x){
      low = mid+1n;
    }
    else{
      high=mid;
    }
  }
  return low.toString();
}

function main() {
    const t = parseInt(readline());
    var inp;
    for (var i = 0; i<t; i++){
        inp = readline().split(" ");
        var k = BigInt(inp[0]);
        var x = BigInt(inp[1]);
        var ans = lower_bound(k,x);
        foo(ans);
    }
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => BigInt(x));

const nsum = n => n*(n+1n)/2n;

function main () {
	let T = rn();
	while (T--) {
		let [k, x] = rna();

		function bs (x, l, r) {
			let mid;
			while (l < r) {
				mid = (l + r) >> 1n;
				if (x > nsum(mid)) {
					l = mid + 1n;
				} else {
					r = mid;
				}
			}
			return l;
		}

		let ans;
		if (x <= nsum(k)) {
			ans = bs(x, 1n, k);
		} else {
			x = x - nsum(k);
			x = nsum(k - 1n) - x + 1n;
			ans = 2n * k - 1n - (bs(x, 1n, k - 1n) - 1n);
		}

		console.log(Number(ans));
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => BigInt(x));

function main () {
	let T = rn();
	while (T--) {
		const [k, x] = rna();

		function bs (x, l, r) {
			let mid;
			while (l < r) {
				mid = (l + r) >> 1n;
				if (x > mid * (mid + 1n)/2n) {
					l = mid + 1n;
				} else {
					r = mid;
				}
			}
			return l;
		}

		let ans;
		if (x <= k*(k+1n)/2n) {
			//console.log('case 1');
			ans = bs(x, 1n, k);
		} else {
			lftx = x - k*(k+1n)/2n;
			lftx = k*(k-1n)/2n - lftx + 1n;
			ans = 2n*k - 1n - (bs(lftx, 1n, k - 1n) - 1n);
		}

		console.log(Number(ans));
	}
}

const readline = require('readline')

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

function solve(k, limit) {
    const cal = x => {
        if (x <= k) {
            return x * (x + 1n) / 2n
        } else {
            const base = k * (k + 1n) / 2n
            return base + (k - 1n + k - 1n - (x - k - 1n)) * (x - k) / 2n
        }
    }
    const count = binarySearch(0n, 2n * k - 1n, x => cal(x) <= limit)
    return cal(count) === limit ? count : min(2n * k - 1n, count + 1n)
}
function min(a, b) {
    return a < b ? a : b
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = ((l + r) / 2n)
        // const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1n
        } else {
            r = m - 1n
        }
    }
    return r
}

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

    something();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function something() {
    const x = parseInt(readline());
    foo(x);
    for (var i=0; i<x; i++){
        var line2 = readline();
        foo(line2);
    }
}
function foo(x) {
    process.stdout.write("hello: ");   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

'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++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = parseInt(readline());
    foo(x);
    for (var i=0; i<x; i++){
        var line2 = readline();
        foo(line2);
    }
}
function foo(x) {
    process.stdout.write("hello: ");   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function find_count(K, y) {
  if (y <= K) {
    return (y * (y + 1n)) / 2n;
  } else {
    return find_count(K, K) * 2n - K - find_count(K, 2n * K - 1n - y);
  }
}

function lower_bound(K, x) {
  let low = 0n;
  let high = 2n * K - 1n;
  while (low < high) {
    let mid = (high + low) / 2n;
    if (find_count(K, mid) < x) {
      low = mid + 1n;
    } else {
      high = mid;
    }
  }
  return low.toString();
}
console.log(lower_bound(BigInt("4"), BigInt("6")));

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const bs = (n, val) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    let to = (mid * (mid + 1n)) / 2n;
    if (to === val) return mid;
    else if (to < val) low = mid + 1n;
    else {
      ans = mid;
      high = mid - 1n;
    }
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, x] = BInpArr();
    let total = n * (n + 1n) - n;
    if (x >= total) console.log(2n * n - 1n + "");
    else {
      let to = (n * (n + 1n)) / 2n;
      if (x < to) {
        console.log(bs(n, x) + "");
      } else if (x > to) {
        console.log(n + bs(n - 1n, x - to) + "");
      } else console.log(n + "");
    }
  }
};
solve();

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const [k, x] = rna();

		function bs (x, l, r) {
			let mid;
			while (l < r) {
				mid = (l + r) >> 1;
				if (x > mid * (mid + 1)/2) {
					l = mid + 1;
				} else {
					r = mid;
				}
			}
			return l;
		}

		let ans;
		if (x <= k*(k+1)/2) {
			//console.log('case 1');
			ans = bs(x, 1, k);
		} else {
			lftx = x - k*(k+1)/2;
			lftx = k*(k-1)/2 - lftx + 1;
			ans = 2*k - 1 - (bs(lftx, 1, k - 1) - 1);
		}

		console.log(ans);
	}
}


//runcommand Get-Content input.txt | node template.js > output.txt or Ctrl+Shift+B
// //libraries
// const heap = require("@datastructures-js/priority-queue");
// const accelerate = require("lodash");
// const linkedlist = require("@datastructures-js/linked-list");
// const { max } = require("lodash");
process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let q = parseInt(readline());
  for (let i = 0; i < q; i++) {
    let ns = readline().split(" ").map(Number);
    let a = readline().split(" ").map(Number);
    print(Detoperations(a, ns[1]));
  }
}

function Detoperations(arr, sum) {
  let n = arr.length;
  let op = 1e20;
  let s = 0;
  let i = 0;
  let j = 0;
  while (i < n && j < n) {
    s += arr[j];
    if (s > sum) op = Math.min(op, n - (j - i));
    while (s > sum) s -= arr[i++];
    j++;
  }
  if (s == sum) op = Math.min(op, n - (j - i));
  if (op == 1e20) return -1;
  return op;
}

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = []
    for (let i = 0; i < arr.length; i++) {
        sum[i] = arr[i]
        if (i) sum[i] += sum[i - 1]
    }
    if (sum[n - 1] < k) return -1
    let max = 0
    for (let i = 0; i < arr.length; i++) {
        const j = binarySearch(i, n - 1, x => sum[x] - (sum[i - 1] || 0) <= k)
        max = Math.max(max, j - i + 1)
    }
// console.log(sum)
    return n - max
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

function solve() {
  const [a, b] = cl().split(' ').map((item) => Number(item));
  const arr = cl().split(' ').map((item) => Number(item));

  let len = 0;

  let r = 0, total = 0;
  for (let i = 0; i < a; i++) {
    if (i > 0) {
      total -= arr[i - 1];
    }
    while (r < a && total + arr[r] <= b) {
      total += arr[r++];
    }
    if (total === b) len = Math.max(r - i, len);
  }

  co(len > 0 ? a - len : -1);

}
function Solution() {
  let n = Number(cl());
  while (n--) {
    solve();
  }
}

function cl() {
  return lines.shift();
}

function co(str) {
  console.log(str);
}

const lines = []

const readline = require('readline')
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
rl.on('line', (input) => {
  lines.push(input);
})
rl.on('close', Solution);

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let sum = 0;
    for (let i = 0; i < n; i++) sum += arr[i];
    if (sum < k) console.log(-1);
    else {
      let sum1 = 0,
        l = 0,
        r = 0,
        res = Infinity;
      while (r < n) {
        sum1 += arr[r];
        if (sum1 > k) {
          while (l <= r && arr[l] !== 1) l++;
          l++;
          sum1 -= 1;
          Math.min(res, n - (r - l + 1));
        } else res = Math.min(res, n - (r - l + 1));
        r++;
      }
      console.log(res);
    }
  }
};
solve();

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}

function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
function abs(x) {
  return x < 0 ? x*(-1) : x;
}
var T = readline();
for(var qe=1;qe<=T;qe++) {
  var [n,s] = readline().split(' ').map((x) => parseInt(x));
  var a = readline().split(' ').map((x) => parseInt(x));
  var pref = []
  pref[0] = 0;
  var inf = 1000000000;
  var ans = -1;
  for(var i=1;i<=n;i++) pref[i] = pref[i-1]+a[i-1]
  var L = 0, R = n;
  while(L <= R) {
    var mid = L + Math.floor((R-L)/2);
    var val = ok(mid);
    if(val <= s) {
      if(val == s) ans = max(ans, mid)
      L = mid+1
    }
    else R = mid-1;
  }
  function ok(x) {
    var mx = -1;
    for(var i=0;i+x<=n;i++) {
      var sum = pref[i+x]-pref[i];
      if(sum == s) return s
      mx = max(mx, sum)
    }
    return mx;
  }
  if(ans != -1) ans = n-ans;
  console.log(ans)
  //fs.appendFileSync('output.txt', ans+'\r\n');

}
//

'use strict';

function solve(n, m, a) {
  const sum = new Array(n);
  const map = new Map();
  map.set(m, -1);
  let res = Infinity;
  for (let [i, num] of a.entries()) {
    var _sum;
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + num;
  }
  for (let i = 0; i < n; i++) {
    if (map.has(sum[i])) {
      res = Math.min(res, n - (i - map.get(sum[i])));
    }
    const t = sum[i] + m;
    if (!map.has(t)) map.set(t, i);
  }
  return res === Infinity ? -1 : res;
}

async function main(read) {
  try {
    let t = Number(await read());
    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);
      res[i] = solve(n, m, a);
    }
    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);
});

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let q = parseInt(readline());
  for (let i = 0; i < q; i++) {
    let ns = readline().split(" ").map(Number);
    let arr = readline().split(" ").map(Number);
    print(Minop(arr, ns[1]));
  }
}

function Minop(arr, sum) {
  let s = 0;
  let op = 0;
  let i = 0;
  let j = arr.length - 1;
  for (let item of arr) s += item;
  if (sum == s) return 0;
  if (sum > s) return -1;
  while (i <= j) {
    if (arr[i] == 1) {
      i++;
      op++;
      s--;
    } else if (arr[j] == 1) {
      j--;
      op++;
      s--;
    } else {
      let temp1 = i;
      let temp2 = j;
      while (i < arr.length && arr[i] !== 1) i++;
      while (j >= 0 && arr[j] !== 1) j--;
      let dis1 = i - temp1;
      let dis2 = temp2 - j;
      if (dis1 < dis2) {
        op += i - temp1;
        j = temp2;
      } else {
        op += temp2 - j;
        i = temp1;
      }
    }
    if (s == sum) return op;
  }
}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let q = parseInt(readline());
  for (let i = 0; i < q; i++) {
    let ns = readline().split(" ").map(Number);
    let arr = readline().split(" ").map(Number);
    print(Minop(arr, ns[1]));
  }
}

function Minop(arr, sum) {
  let s = 0;
  let op = 0;
  let i = 0;
  let j = arr.length - 1;
  let rec1 = 1e9;
  let rec2 = 1e9;
  let pre = [];
  let suff = [];
  for (let k = 0; k < arr.length; k++) {
    if (arr[k] == 1) {
      s++;
      rec1 = k;
    }
    if (arr[arr.length - k - 1] == 1) rec2 = arr.length - k - 1;
    if (arr[k] == 0) pre[k] = rec1 == 1e9 ? rec1 : k - rec1;
    if (arr[arr.length - k - 1] == 0) suff[arr.length - k - 1] = rec2 == 1e9 ? rec2 : rec2 - (arr.length - k - 1);
  }
  if (sum == s) return 0;
  if (sum > s) return -1;
  while (i <= j) {
    if (arr[i] == 1) {
      i++;
      op++;
      s--;
    } else if (arr[j] == 1) {
      j--;
      op++;
      s--;
    } else {
      if (pre[j] < suff[i]) j--;
      else i++;
      op++;
    }
    if (s == sum) return op;
  }
}

function solve() {
  const [a, b] = cl().split(' ').map((item) => Number(item));
  const arr = cl().split(' ').map((item) => Number(item));
  let total = arr.reduce((pre, curr) => pre + curr);

  if (total < b) return co(-1);
  const arr1= new Array(a).fill(0);
  let target = Infinity;
  for (let i = a - 1; i >= 0; i--) {
    if (arr[i] === 1) target = i;
    arr1[i] = target;
  }

  const arr2 = new Array(a).fill(0);
  target = Infinity;
  for (let i = 0; i < a; i++) {
    if (arr[i] === 1) target = a - i - 1;
    arr2[i] = target;
  }

  let l = 0, r = a - 1;
  while (total > b) {
    if (arr[l] === 1) {
      l += 1;
      total -= 1;
    }
    else if (arr[r] === 1) {
      r -= 1;
      total -= 1;
    }
    else {
      if (arr1[l] <= arr2[r]) {
        l += 1;
      } else {
        r -= 1;
      }
    }
  }

  co(l + arr.length - 1 - r);
}
function Solution() {
  let n = Number(cl());
  while (n--) {
    solve();
  }
}

function cl() {
  return lines.shift();
}

function co(str) {
  console.log(str);
}

const lines = []

const readline = require('readline')
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
rl.on('line', (input) => {
  lines.push(input);
})
rl.on('close', Solution);

function solve() {
  const [_, b] = cl().split(' ').map((item) => Number(item));
  const arr = cl().split(' ').map((item) => Number(item));
  let total = arr.reduce((pre, curr) => pre + curr);

  if (total < b) return co(-1);

  let l = 0, r = arr.length - 1;
  let lastL = 0, lastR = arr.length - 1;
  while (total > b) {
    if (arr[l] === 1) {
      r = lastR;
      l += 1;
      lastL = l;
      total -= 1;
    } else if (arr[r] === 1) {
      l = lastL;
      r -= 1;
      lastR = r;
      total -= 1;
    } else {
      l += 1;
      r -= 1;
    }
  }
  co(l + arr.length - 1 - r);
}
function Solution() {
  let n = Number(cl());
  while (n--) {
    solve();
  }
}

function cl() {
  return lines.shift();
}

function co(str) {
  console.log(str);
}

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
const lines = []
rl.on('line', (input) => {
  lines.push(input);
})
rl.on('close', Solution);

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let sum = 0;
    for (let i = 0; i < n; i++) sum += arr[i];
    if (sum < k) console.log(-1);
    else if (sum === k) console.log(0);
    else {
      let i,
        j,
        cnt = 0;
      for (i = 0; i < n; i++) {
        if (sum === k) break;
        if (arr[i] === 0) break;
        sum--;
        cnt++;
      }
      if (sum === k) {
        console.log(cnt);
        continue;
      }
      for (j = n - 1; j >= 0; j--) {
        if (sum === k) break;
        if (arr[j] === 0) break;
        sum--;
        cnt++;
      }
      if (sum === k) {
        console.log(cnt);
        continue;
      }
      let cnt1 = 0,
        cnt2 = 0,
        s1 = sum,
        s2 = sum;
      while (i < n) {
        if (s1 === k) break;
        if (arr[i] === 1) s1--;
        cnt1++;
        i++;
      }
      while (j >= 0) {
        if (s2 === k) break;
        if (arr[j] === 1) s2--;
        j--;
        cnt2++;
      }
      console.log(cnt + Math.min(cnt1, cnt2));
    }
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let sum = 0;
    for (let i = 0; i < n; i++) sum += arr[i];
    if (sum < k) console.log(-1);
    else if (sum === k) console.log(0);
    else {
      let left = [],
        right = [];
      for (let i = 0; i < n; i++) {
        if (arr[i] === 1) left[i] = 0;
        else {
          let cnt = 0;
          for (let j = i; j < n; j++) {
            if (arr[j] === 1) break;
            else cnt++;
          }
          left[i] = cnt;
        }
      }
      for (let i = n - 1; i >= 0; i--) {
        if (arr[i] === 1) right[i] = 0;
        else {
          let cnt = 0;
          for (let j = i; j >= 0; j--) {
            if (arr[j] === 1) break;
            else cnt++;
          }
          right[i] = cnt;
        }
      }
      let i = 0,
        j = n - 1,
        cnt = 0;
      while (cnt < n) {
        if (sum === k) break;
        if (arr[i] === 1) {
          sum--;
          i++;
        } else if (arr[j] === 1) {
          j--;
          sum--;
        } else {
          if (left[i] < right[j]) i++;
          else j--;
        }
        cnt++;
      }
      console.log(cnt);
    }
  }
};
solve();


const processData = (lines) => {
  const [n, a, b, k] = lines[0].split(' ').map(x => +x)
  const hps = lines[1].split(' ').map(x => +x)

  const notSoEasyKill = []

  let exp = 0

  const totalDamage = a + b

  for (let i = 0; i<hps.length; i++) {
    const hp = hps[i]
    let leftHp = hp%totalDamage
    if (leftHp === 0) {
      leftHp = totalDamage
    }
    if (leftHp <= a) {
      exp++
    } else {
      notSoEasyKill.push(leftHp - a)
    }
  }

  let leftSkills = k

  const lefts = notSoEasyKill
    .reduce((r, x) => {const key = Math.ceil(x/a); r[key] = r[key] ? r[key] + 1 : 1; return r;}, {})

  const keys = Object.keys(lefts).map(x => +x).sort((a, b) => a - b)
  let i = 0
  while (leftSkills > 0 && i < keys.length) {
    const key = keys[i]
    const left = lefts[key]
    if (left * key > leftSkills) {
      exp += Math.floor(leftSkills / key)
      leftSkills = 0
    } else {
      leftSkills -= left * key
      exp += left
    }
    i++
  }

  console.log(exp)
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

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

const input = [];
readline.on('line', x => input.push(x));

readline.on('close', () => {
    let [n, a, b, k] = input[0].split(' ').map(x => parseInt(x));

    scores = 0;
    let helps = [];
    const monsters = input[1].split(' ').map(
        x => {
            x = parseInt(x);
            let hp = x - a;
            let sum_power = b + a;
            let last_hit_hp = hp - sum_power * Math.trunc(hp / sum_power);

            if (last_hit_hp <= b) helps.push(Math.ceil(last_hit_hp / a));
            else scores++;

            return x;
        }
    );

    helps.sort((a, b) => a - b);
    for (let i = 0; i < helps.length; i++) {
        k -= helps[i];
        if (k >= 0) scores++;
        else break;
    }

    console.log(scores);
});

    'use strict'

    const params = readline().split(' ').map(num => parseInt(num))
    const arr = readline().split(' ').map(num => parseInt(num))

    const a = params[1]
    const b = params[2]
    let k = params[3]

    const all = Array(params[0]).fill(0)
    for (let i in arr) {
      let val = parseInt(arr[i] %  (a + b))

      if (val === 0) {
        val += b
      } else {
        val = Math.max(0, val - a)
      }
      all[i] = parseInt(Math.ceil(val / a))
    }

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

    let ans = 0
    for (let i in all) {
      if (k - all[i] < 0) break
      ans ++
      k -= all[i]
    }

    print(ans)

'use strict'

const problem = (n, a, b, k, h) => {
    let d = {};
    let res = 0;
    for (let i = 0; i < n; i++) {
        const hp = (h[i] - 1) % (a+b) + 1 - a;
        if (hp > 0) {
            if (d[hp]) d[hp]++;
            else d[hp] = 1;
        } else {
            res++;
        }
    }

    const monsters = Object.keys(d).sort((x, y) => x-y);
    for (let i = 0; i < monsters.length; i++) {
        const hp = monsters[i];
        const cnt = d[hp];
        const hits = (hp / a | 0) + ((hp % a) ? 1 : 0);
        if (k < cnt * hits) return res + k / hits | 0;
        res += cnt;
        k -= cnt * hits;
    }
    return res;
}

const nabk = readline().split(' ').map(i => +i);
const h = readline().split(' ').map(i => +i);
print(problem(nabk[0], nabk[1], nabk[2], nabk[3], h))

'use strict'

const params = readline().split(' ').map(num => parseInt(num))
const arr = readline().split(' ').map(num => parseInt(num))

const a = params[1]
const b = params[2]
let k = params[3]

const all = Array(params[0]).fill(0)
for (let i in arr) {
  let val = parseInt(arr[i] %  (a + b))

  if (val === 0) {
    val += b
  } else {
    val = Math.max(0, val - a)
  }
  all[i] = parseInt(Math.ceil(val / a))
}

all.sort()

let ans = 0
for (let i in all) {
  if (k - all[i] < 0) break
  ans ++
  k -= all[i]
}

print(ans)

const processData = (lines) => {
  const [n, a, b, k] = lines[0].split(' ').map(x => +x)
  const hps = lines[1].split(' ').map(x => +x)

  const notSoEasyKill = []

  let exp = 0

  const totalDamage = a + b

  for (let i = 0; i<hps.length; i++) {
    const hp = hps[i]
    let leftHp = hp%totalDamage
    if (leftHp === 0) {
      leftHp = totalDamage
    }
    if (leftHp <= a) {
      exp++
    } else {
      notSoEasyKill.push(leftHp)
    }
  }

  let leftSkills = k

  const lefts = notSoEasyKill
    .reduce((r, x) => {const key = Math.floor(x/a); r[key] = r[key] ? r[key] + 1 : 1; return r;}, {})

  const keys = Object.keys(lefts).map(x => +x).sort((a, b) => a - b)
  let i = 0
  while (leftSkills > 0 && i < keys.length) {
    const key = keys[i]
    const left = lefts[key]
    if (left * key > leftSkills) {
      exp += Math.ceil(leftSkills / key)
      leftSkills = 0
    } else {
      leftSkills -= left * key
      exp += left
    }
    i++
  }

  console.log(exp)
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})

const processData = (lines) => {
  const [n, a, b, k] = lines[0].split(' ').map(x => +x)
  const hps = lines[1].split(' ').map(x => +x)

  const notSoEasyKill = []

  let exp = 0

  const totalDamage = a + b

  for (let i = 0; i<hps.length; i++) {
    const hp = hps[i]
    let leftHp = hp%totalDamage
    if (leftHp === 0) {
      leftHp = totalDamage
    }
    if (leftHp <= a) {
      exp++
    } else {
      notSoEasyKill.push(leftHp - a)
    }
  }

  let leftSkills = k

  const lefts = notSoEasyKill
    .reduce((r, x) => {const key = Math.ceil(x/a); r[key] = r[key] ? r[key] + 1 : 1; return r;}, {})

  const keys = Object.keys(lefts).map(x => +x).sort((a, b) => a - b)
  let i = 0
  while (leftSkills > 0 && i < keys.length) {
    const key = keys[i]
    const left = lefts[key]
    if (left * key > leftSkills) {
      exp += Math.ceil(leftSkills / key)
      leftSkills = 0
    } else {
      leftSkills -= left * key
      exp += left
    }
    i++
  }

  console.log(exp)
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})


var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value.trim();
const rn = () => BigInt(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => BigInt(x));

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const INF = 2e18;

// same as cpp bound functions
// lowerBound(ar, x) - first element >= x, return ar.length if no such element is found
// upperBound(ar, x) - first element > x, return ar.length if no such element is found
function lowerBound (ar, x) {
	let l = 0, r = ar.length;
	while (r-l > 1) {
		const mid = l+r >> 1;
		if (ar[mid] >= x) {
			r = mid;
		} else {
			l = mid;
		}
	}
	return ar[l] >= x ? l : r;
}

function upperBound (ar, x) {
	let l = 0, r = ar.length;
	while (r-l > 1) {
		const mid = l+r >> 1;
		if (ar[mid] <= x) {
			l = mid + 1;
		} else {
			r = mid;
		}
	}
	return a[l] > x ? l : r;
}

const max = (a, b) => a > b ? a : b;
const min = (a, b) => a < b ? a : b;

function main () {
	const n = rn();
	const a = rna();
	const m = rn();
	const x = [], y = [];
	for (let i = 0; i < m; i++) [x[i], y[i]] = rna();

	let powerSum = 0n;
	for (let i = 0; i < n; i++) powerSum += a[i];

	for (let i = 0; i < n; i++) a[i] = Number(a[i]);
	a.sort((x, y) => x - y);
	//for (let i = 0; i < n; i++) a[i] = BigInt(a[i]);

	for (let i = 0; i < m; i++) x[i] = Number(x[i]);

	for (let i = 0; i < m; i++) {
		const lb = lowerBound(a, x[i]);
		let option1 = INF, option2 = INF;
		if (lb < n) option1 = max(0n, y[i] - (powerSum - BigInt(a[lb])));
		if (lb > 0) option2 = BigInt(x[i] - a[lb-1]) + max(0n, y[i] - (powerSum - BigInt(a[lb-1])));

		console.log(min(option1, option2).toString());
	}
}

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value.trim();
const rn = () => Number(rl());
const rbn = () => BigInt(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));
const rbna = () => ra().map(x => BigInt(x));

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const INF = 2e18;

// same as cpp bound functions
// lowerBound(ar, x) - first element >= x, return ar.length if no such element is found
// upperBound(ar, x) - first element > x, return ar.length if no such element is found
function lowerBound (ar, x) {
	let l = 0, r = ar.length;
	while (r-l > 1) {
		const mid = l+r >> 1;
		if (ar[mid] >= x) {
			r = mid;
		} else {
			l = mid;
		}
	}
	return ar[l] >= x ? l : r;
}

function upperBound (ar, x) {
	let l = 0, r = ar.length;
	while (r-l > 1) {
		const mid = l+r >> 1;
		if (ar[mid] <= x) {
			l = mid + 1;
		} else {
			r = mid;
		}
	}
	return a[l] > x ? l : r;
}

const max = (a, b) => a > b ? a : b;
const min = (a, b) => a < b ? a : b;
const B = a => BigInt(a);

function main () {
	const n = rn();
	const a = rna();
	const m = rn();

	let powerSum = 0n;
	for (let i = 0; i < n; i++) powerSum += B(a[i]);
	a.sort((x, y) => x - y);

	for (let i = 0; i < m; i++) {
		let [x, y] = rbna(); x = Number(x);

		let option1 = INF, option2 = INF;
		const j = lowerBound(a, x);
		if (j < n) option1 = max(0n, y - (powerSum - B(a[j])));
		if (j > 0) option2 = B(x) - B(a[j-1]) + max(0n, y - (powerSum - B(a[j-1])));

		console.log(min(option1, option2).toString());
	}
}

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value.trim();
const rn = () => Number(rl());
const rbn = () => BigInt(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));
const rbna = () => ra().map(x => BigInt(x));

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const INF = 2e18;

// same as cpp bound functions
// lowerBound(ar, x) - first element >= x, return ar.length if no such element is found
// upperBound(ar, x) - first element > x, return ar.length if no such element is found
function lowerBound (ar, x) {
	let l = 0, r = ar.length;
	while (r-l > 1) {
		const mid = l+r >> 1;
		if (ar[mid] >= x) {
			r = mid;
		} else {
			l = mid;
		}
	}
	return ar[l] >= x ? l : r;
}

function upperBound (ar, x) {
	let l = 0, r = ar.length;
	while (r-l > 1) {
		const mid = l+r >> 1;
		if (ar[mid] <= x) {
			l = mid + 1;
		} else {
			r = mid;
		}
	}
	return a[l] > x ? l : r;
}

const max = (a, b) => a > b ? a : b;
const min = (a, b) => a < b ? a : b;
const B = a => BigInt(a);

function main () {
	const n = rn();
	const a = rna();
	const m = rn();
	const x = [], y = [];
	for (let i = 0; i < m; i++) [x[i], y[i]] = rbna();
	for (let i = 0; i < m; i++) x[i] = Number(x[i]);

	let powerSum = 0n;
	for (let i = 0; i < n; i++) powerSum += B(a[i]);
	a.sort((x, y) => x - y);

	for (let i = 0; i < m; i++) {
		const lb = lowerBound(a, x[i]);
		let option1 = INF, option2 = INF;
		if (lb < n) option1 = max(0n, y[i] - (powerSum - B(a[lb])));
		if (lb > 0) option2 = B(x[i]) - B(a[lb-1]) + max(0n, y[i] - (powerSum - B(a[lb-1])));

		console.log(min(option1, option2).toString());
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function lowerBound(arr, x) {
	for (let i = 1; i < arr.length; i++)
		if (x < arr[i]) return i - 1;
	return arr.length - 1;
}

const INF = Number.POSITIVE_INFINITY;

function main () {
	let n = rn();
	let a = rna();
	let m = rn();

	a.sort((x, y) => x - y);

	let sm = 0;
	for (elm of a) sm +=elm;

	while (m--) {
		let [x, y] = rna();

		const l = lowerBound(a, x);
		ansl = Math.max(0, y - (sm - a[l])) + Math.max(0, x - a[l]);
		ansr =  l + 1 < n ? Math.max(0, y - (sm - a[l+1])) : INF;
		const ans = Math.min(ansl, ansr);

		console.log(ans);
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let n = rn();
	let a = rna();
	let m = rn();
	let x = [], y = [];
	for (let i = 0; i < m; i++)
		[x[i], y[i]] = rna();

	a.sort((x, y) => x - y);

	let sm = 0;
	for (elm of a) sm +=elm;

	for (let i = 0; i < m; i++) {
		let ans = 0;
		if (x[i] <= a[0]) {
			ans = Math.max(y[i] - (sm - a[0]), 0);
		} else if (x[i] >= a[n-1]) {
			ans = Math.max(y[i] - (sm - a[n-1]), 0) + x[i] - a[n-1];
		} else {
			for (let j = 0; j < n; j++) {
				if (x[i] >= a[j] && x[i] < a[j+1]) {
					ans1 = Math.max(y[i] - (sm - a[j+1]), 0); // select higher powered soldier
					ans2 = Math.max(y[i] - (sm - a[j]), 0) + x[i] - a[j]; // select lower ...
					ans = Math.min(ans1, ans2);
					break;
				}
			}
		}
		console.log(ans);
	}
}


// var lineIdx = 0;
// var readline = () => {
//   var input = ["3", "3 3", "1 2 3", "3 4", "1 2 3", "2 2" ,"0 6"]
//   return input[lineIdx++];
// };
// var print = (str) => {
//   console.log(str);
// };

var t = readline().split(" ").map(function (x) { return parseInt(x); })[0];

var step = () => {
  var input = readline().split(" ").map(function (x) { return parseInt(x); });
  var n = input[0];
  var x = input[1];

  var row = readline().split(" ").map(function (x) { return parseInt(x); });

  var max = -2;

  var sum = 0;
  for (var i = 0; i < n; i ++){
    sum += row[i];
    sum = sum % x;
    if(sum != 0){
      max = i;
    }
  }

  sum = 0;
  for (i = n-1; i >= 0; i --){
    sum += row[i];
    sum = sum % x;
    if(sum != 0){
      if(n -1 - i > max){
         max = n -1 - i;
      }
    }
  }

  print(max + 1)

}

for (var i2 = 0; i2 < t; i2++) {
  step();
}

var na = readline();
var maxa = [];
var inp = [];
for (var i = 0;i<na;i++){
    maxa.push(parseInt(readline().split(" ")[1]));
    inp.push(readline().split(" ").map(function (a) {
        return parseInt(a);
    }));
}
for (var j = 0;j<na;j++) {
    var n = inp[j].length, x = maxa[j], sum = 0, l = -1, r=0;
    for (var i = 0; i < n; i++) {
        var a = inp[j][i];
        if (a % x) {
            if (l === -1)
                l = i;
            r = i;
        }
        sum += a;
    }
    if (sum % x) {
        write(n + "\n");

    } else if (l === -1) {
        write("-1\n");
    } else {
        write(n - ((l + 1 < n - r) ? l + 1 : n - r) + "\n");
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
var input = '';
process.stdin.on('data', function (line) {
    input += line;
});
process.stdin.on('end', function () {
    var lines = input.split('\n');
    var tests = parseInt(lines.shift(), 10);
    var _loop_1 = function () {
        var nx = lineToNumArray(lines.shift());
        var n = nx[0], x = nx[1];
        var arr = lineToNumArray(lines.shift());
        var distFromBegin = arr.findIndex(function (element) { return element % x !== 0; });
        var distFromEnd = arr.reverse().findIndex(function (element) { return element % x !== 0; });
        if (distFromBegin === -1) {
            console.log(-1);
        }
        else {
            var sum = arr.reduce(function (a, b) { return a + b; }, 0);
            console.log(sum % x !== 0 ?
                n :
                n - Math.min(distFromBegin, distFromEnd) - 1);
        }
    };
    while (tests--) {
        _loop_1();
    }
});
// input helper
function lineToNumArray(line) {
    return line.split(' ').map(function (element) { return parseInt(element, 10); });
}

function solve() {
   var T = Number(read());
   for (var t = 0; t < T; ++t) {
      var nx = read().split(' ').map(Number);
      var n = nx[0];
      var x = nx[1];
      var a = read().split(' ').map(Number);
      var ax = [[-1]];
      var sx = 0;
      for (var i = 0; i < n; ++i) {
         sx = (sx + a[i]) % x;
         if (ax[sx]) {
            ax[sx].push(i);
         } else {
            ax[sx] = [i];
         }
      }
      var ans = -1;
      for (var i = 0; i < x; ++i) {
         if (!ax[i]) {
            continue;
         }
         for (var j = i + 1; j < x; ++j) {
            if (!ax[j]) {
               continue;
            }
            var i1 = ax[i][0];
            var i2 = ax[i][ax[i].length - 1];
            var j1 = ax[j][0];
            var j2 = ax[j][ax[j].length - 1];
            if (i1 < j2 && j2 - i1 > ans) {
               ans = j2 - i1;
            }
            if (j1 < i2 && i2 - j1 > ans) {
               ans = i2 - j1;
            }
         }
      }
      write(ans);
   }
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         solve();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', solve);
   }
} else {
   solve();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
var input = '';
process.stdin.on('data', function (line) {
    input += line;
});
process.stdin.on('end', function () {
    var lines = input.split('\n');
    var tests = parseInt(lines.shift(), 10);
    var _loop_1 = function () {
        var nx = lineToNumArray(lines.shift());
        var n = nx[0], x = nx[1];
        var arr = lineToNumArray(lines.shift());
        var allDivisible = arr.every(function (element) { return element % x === 0; });
        if (allDivisible) {
            console.log(-1);
        }
        else {
            var sum = arr.reduce(function (a, b) { return a + b; }, 0);
            console.log(sum % x !== 0 ? n : n - 1);
        }
    };
    while (tests--) {
        _loop_1();
    }
});
// input helper
function lineToNumArray(line) {
    return line.split(' ').map(function (element) { return parseInt(element, 10); });
}

var n = readline();
var maxa = [];
var inp = [];
for (var i = 0;i<n;i++){
    maxa.push(parseInt(readline().split(" ")[1]));
    inp.push(readline().split(" ").map(function (a) {
        return parseInt(a);
    }));
}
for (var i = 0;i<n;i++) {
    var max = -1;
    for (var j = 0;j<inp[i].length;j++) {
        var tmpSum = 0;
        var llen = 0;
        if (max>inp[i].length - j){
            break;
        }
        for (var k = j; k < inp[i].length; k++) {
            if ((tmpSum + inp[i][k]) === 0  || (tmpSum + inp[i][k]) % maxa[i] === 0){
                break;
            }else{
                tmpSum += inp[i][k];
                llen ++;
            }
        }
        if (llen !== 0 && llen>max){
            max = llen;
        }
    }
    write(max + "\n");
}


var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		let n = rn();
		let a = rna();

		let pwr = 1, mxx = 0, sm = 0;
		for (let x of a) {
			while (x % 2 == 0) {
				pwr *= 2;
				x /= 2;
			}
			mxx = Math.max(mxx, x);
			sm += x;
		}

		ans = sm - mxx + mxx*pwr;
		console.log(ans);
	}
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var a = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});
            var ans = '';
            var two = 1, max = 0, sum = 0;
            for(j = 0; j < n; j++){
                while(a[j] % 2 === 0){
                    a[j] /= 2;
                    two *= 2;
                }
                max = Math.max(max, a[j]);
                sum += a[j];
            }
            var b = sum - max;
            two *= max;
            console.log(b + two);
        }
    }
});


const readline = require('readline')

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

function solve(str) {
    const ch = []
    const map = {}
    for (let i = str.length - 1; i >= 0; i--) {
        if (ch.indexOf(str[i]) < 0) {
            ch.unshift(str[i])
        }
        map[str[i]] = (map[str[i]] || 0) + 1
    }
// console.log(map, ch)
    let sum = 0
    for (let i = 0; i < ch.length; i++) {
        const c = ch[i]
        const k = map[c]
        // if (i === ch.length - 1) {
        //     sum += k
        //     break
        // }
        if (k % (i + 1)) return -1

        sum += k / (i + 1)
    }
    const old = str.slice(0, sum)

    const d = {}
    let p = 0
    for (let i = 0; i < ch.length; i++) {
        for (let j = 0; j < sum; j++) {
            if (!d[old[j]]) {
                if (str[p] !== old[j]) return -1
                p++
            }
        }
        const c = ch[i]
        d[c] = 1
    }

    return old + ' ' + ch.join('')
}

let inputs = []

function read() {
    return inputs.pop();
}

function readInt() {
    return parseInt(read());
}

function solve() {
    let test = readInt();
    while (test--) {
        let t = read();
        used = new Array(256);
        for (let i = 0; i < 256; i++) {
            used[i] = 0;
        }
        let s = '';
        let sq = '';
        for (let i = t.length - 1; 0 <= i; i--) {
            let c = t.charCodeAt(i);
            if (!used[c]) {
                sq += t[i];
            }
            used[c] += 1;
        }
        sq = sq.split("").reverse().join("");
        cnt = new Array(256);
        for (let i = 0; i < 256; i++) {
            cnt[i] = 0;
        }
        cnt2 = new Array(256);
        for (let i = 0; i < 256; i++) {
            cnt2[i] = 0;
        }
        for (let i = 0; i < sq.length; i++) {
            let c = sq.charCodeAt(i);
            cnt[c] = parseInt(used[c] / (i + 1));
        }
        let num = 0;
        for (let i = 0; i < t.length; i++) {
            let c = t.charCodeAt(i);
            cnt2[c]++;
            if (cnt[c] == cnt2[c]) {
                num++;
            }
            s += t[i];
            if (num == sq.length) {
                break;
            }
        }
        if (s == '') {
            console.log(-1);
            continue;
        }
        for (let i = 0; i < 256; i++) {
            used[i] = 0;
        }
        let t2 = '';
        for (let i = 0; i < sq.length; i++) {
            for (let j = 0; j < s.length; j++) {
                let c = s.charCodeAt(j);
                if (!used[c]) {
                    t2 += s[j];
                }
            }
            let c = sq.charCodeAt(i);
            used[c] = 1;
        }
        if (t == t2) {
            console.log(s + ' ' + sq);
        }
        else {
            console.log(-1);
        }
    }
}

function main() {
    inputs = inputString.trim().split(/\n| /).map((string) => string.trim());
    inputs.reverse();
    solve();
}

let inputString = '';

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

process.stdin.on('end', (_) => { main(); });

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readLineAsNumber() {
    return Number(this.readLine())
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(String(e))
  }
  println(e) {
    stdout.write(String(e)), stdout.write('\n')
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(t => {
      stdin.on('data', t => e.push(t)),
        stdin.on('end', function () {
          const n = e.join('').split(os.EOL)
          t(n)
        })
    })
  }
}
async function __main__(e) {
  const t = new InputAndOutput()
  await t.init(), e(t)
}
function solve(e) {
  let t = []
  const n = {}
  for (let i = e.length - 1; i >= 0; --i) {
    const s = e[i]
    let r = n[s]
    void 0 === r ? (t.push(s), (r = 1)) : (r += 1), (n[s] = r)
  }
  const i = t.length
  let s = 0
  for (let e = 0; e < i; ++e) {
    const r = n[t[e]]
    if (r % (i - e) != 0) return -1
    s += r / (i - e)
  }
  t = t.reverse()
  let r = e.slice(0, s)
  for (let n = 0, o = s; n < i; ++n) {
    r = r.replace(new RegExp(t[n], 'g'), '')
    for (let t = 0; t < r.length; ++t) if (r[t] != e[o++]) return -1
  }
  return e.slice(0, s).concat(' ').concat(t.join(''))
}
__main__(function (e) {
  const t = e.readLineAsNumber()
  for (let n = 1; n <= t; ++n) {
    const t = solve(e.readLine())
    e.print(t + '\n')
  }
})


const firstLine = readline();
const n = firstLine.split(' ')[0];
const m = firstLine.split(' ')[1];
const firstArray = readline().split(' ').map(function(x) {
    return parseInt(x);
});
const secondArray = readline().split(' ').map(function(x) {
    return parseInt(x);
});

var result = 0;
var i = 0,
    j = 0,
    firstSum = firstArray[0],
    secondSum = secondArray[0];

while (i < firstArray.length && j < secondArray.length){
    if (firstSum > secondSum){
        j++;
        secondSum += secondArray[j];
        continue;
    }
    if (firstSum < secondSum){
        i++;
        firstSum += firstArray[i];
        continue;
    }
    if (firstSum === secondSum){
        result++;
        i++;
        firstSum = firstArray[i];
        j++;
        secondSum = secondArray[j];
    }
}

print(result);

var firstLine = readline().split(' ').map(function(v){return +v;});
var secondLine = readline().split(' ').map(function(v){return +v;});
var thirdLine = readline().split(' ').map(function(v){return +v;});

var aCount = firstLine[0];
var bCount = firstLine[1];
var a = secondLine;
var b = thirdLine;

var curA = a[0];
var curB = b[0];
var result = 0;

var i = 0;
var j = 0;

while (true) {
    if (curA == curB) {
        i++;
        j++;

        if (i > aCount) break;
        if (j > bCount) break;

        result++;

        curA = a[i];
        curB = b[j];
        continue;
    }

    if (curA > curB) {
        j++;
        curB += b[j];
        continue;
    }

    if (curA < curB) {
        i++;
        curA += a[i];
    }
}

print(result);


var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value;
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		let [n, a, b] = rna();

		if (a+b > n-2 || Math.abs(a-b) > 1) {
			console.log(-1);
			continue;
		}

		const ans = [];
		for (let i = 0; i < n; i++) ans.push(i+1);

		let i = 0;
		if (a == b) i = 1;
		else if (a > b) ans.reverse();

		let cnt = Math.max(a, b);
		while (cnt--) {
			[ans[i], ans[i+1]] = [ans[i+1], ans[i]];
			i += 2;
		}

		//console.log({cnt, ans, a, b})

		console.log(ans.join(' '));
	}
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, a, b] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (a + b + 2 > n || Math.abs(a - b) > 1) {
      console.log(-1);
      continue;
    }
    let c = false;
    if (a < b) {
      [a, b] = [b, a];
      c = true;
    }
    let sI = n - a - b - 1;
    let res = [],
      obj = {},
      narr = new Array(n).fill(1).map((cur, ind) => ind + 1);
    for (let i = sI, j = n; i < n; i += 2, j--) obj[j] = res[i] = j;
    let sar = [];
    for (let i = 0; i < n; i++) if (!obj[narr[i]]) sar.push(narr[i]);
    for (let i = 0, j = 0; i < n; i++) if (!res[i]) res[i] = sar[j++];
    if (c) for (let i = 0; i < n; i++) res[i] = n + 1 - res[i];
    console.log(res.join(" "));
  }
};
solve();

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value;
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		let [n, a, b] = rna();

		if (a+b <= n-2 && Math.abs(a-b) <= 1) {

			let cur = 0, diff = 0, sign = 1, mn = 0;

			if (a < b) sign = -1;
			const ans = [0];
			for (let i = 0; i < n-1; i++) {
				if (cur > 0 && a) {
					a--;
					sign *= -1;
				} else if (cur < 0 && b) {
					b--;
					sign *= -1;
				} else {
					diff = 0;
				}
				diff++;

				cur = cur + diff*sign;
				ans.push(cur);

				mn = Math.min(mn, cur);
			}

			//console.log({ans, a, b})
			for (let i = 0; i < n; i++)
				ans[i] += 1 - mn;

			console.log(ans.join(' '));

		} else {
			console.log(-1);
		}

	}
}

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value;
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		let [n, a, b] = rna();

		if (a+b > n-2 || Math.abs(a-b) > 1) {
			console.log(-1);
			continue;
		}

		let cur, mn = 0;
		if (a > b) cur = 1;
		else cur = -1;

		const ans = [0, cur];

		for (let i = 0; i < n-2; i++) {
			if (cur > 0 && a) {
				a--;
				cur = -cur;
			} else if (cur < 0 && b) {
				b--;
				cur = -cur + 1;
			} else {
				cur += cur > 0 ? 1 : -1;
			}

			ans.push(cur);

			mn = Math.min(mn, cur);
		}

		//console.log({a, b, mn})
		for (let i = 0; i < n; i++)
			ans[i] += 1 - mn;

		console.log(ans.join(' '));
	}
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, a, b] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (a + b + 2 > n || Math.abs(a - b) > 1) {
      console.log(-1);
      continue;
    }
    let c = false;
    if (a < b) {
      [a, b] = [b, a];
      c = true;
    }
    let start = n - a;
    let sI = n - a - b - 1;
    let res = [],
      obj = {},
      narr = new Array(n).fill(1).map((cur, ind) => ind + 1);
    for (let i = sI, j = start; i < n; i += 2, j++) obj[j] = res[i] = j;
    let sar = [];
    for (let i = 0; i < n; i++) if (!obj[narr[i]]) sar.push(narr[i]);
    for (let i = 0, j = 0; i < n; i++) if (!res[i]) res[i] = sar[j++];
    if (c) for (let i = 0; i < n; i++) res[i] = n + 1 - res[i];
    console.log(res.join(" "));
  }
};
solve();