You are given a binary string of length $$$n$$$. You have exactly $$$k$$$ moves. In one move, you must select a single bit. The state of all bits except that bit will get flipped ($$$0$$$ becomes $$$1$$$, $$$1$$$ becomes $$$0$$$). You need to output the lexicographically largest string that you can get after using all $$$k$$$ moves. Also, output the number of times you will select each bit. If there are multiple ways to do this, you may output any of them.A binary string $$$a$$$ is lexicographically larger than a binary string $$$b$$$ of the same length, if and only if the following holds:   in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ contains a $$$1$$$, and the string $$$b$$$ contains a $$$0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Each test case has two lines. The first line has two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$0 \leq k \leq 10^9$$$). The second line has a binary string of length $$$n$$$, each character is either $$$0$$$ or $$$1$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output two lines. The first line should contain the lexicographically largest string you can obtain. The second line should contain $$$n$$$ integers $$$f_1, f_2, \ldots, f_n$$$, where $$$f_i$$$ is the number of times the $$$i$$$-th bit is selected. The sum of all the integers must be equal to $$$k$$$.

NoteHere is the explanation for the first testcase. Each step shows how the binary string changes in a move.  Choose bit $$$1$$$: $$$\color{red}{\underline{1}00001} \rightarrow \color{red}{\underline{1}}\color{blue}{11110}$$$.  Choose bit $$$4$$$: $$$\color{red}{111\underline{1}10} \rightarrow \color{blue}{000}\color{red}{\underline{1}}\color{blue}{01}$$$.  Choose bit $$$4$$$: $$$\color{red}{000\underline{1}01} \rightarrow \color{blue}{111}\color{red}{\underline{1}}\color{blue}{10}$$$.  The final string is $$$111110$$$ and this is the lexicographically largest string we can get.

"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 solve = () => {
  let t = getValue();
  while (t--) {
    let [n, k] = iInpArr();
    let arr = iInpArr1();
    let res = new Array(n).fill(0);
    if (k % 2 === 1) {
      let flag = 0;
      for (let i = 0; i < n - 1; i++) {
        if (arr[i] === 0) arr[i] = 1;
        else if (arr[i] === 1 && flag === 0) {
          res[i]++;
          flag = 1;
        } else arr[i] = 0;
      }
      if (flag === 1) arr[n - 1] = arr[n - 1] === 0 ? 1 : 0;
      else res[n-1]++;
      k--;
    }
    for (let i = 0; i < n; i++) {
      if (i === n - 1 && k > 0) {
        if (k % 2 !== 0) arr[i] = arr[i] === 0 ? 1 : 0;
        res[i] += k;
      } else if (arr[i] === 0 && k > 0) {
        arr[i] = 1;
        res[i]++;
        k--;
      }
    }
    console.log(arr.join(""));
    console.log(res.join(" "));
  }
};
solve();

'use strict';
const readline = require('readline');
const util = require('util');
const lineReader = readline.createInterface({
    input: process.stdin,
});
let inputPos = 0;
const inputWords = [];
lineReader.on('line', (line) => {
    inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));
});
lineReader.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(inputWords[inputPos++]));
}
function nextStr() {
    return inputWords[inputPos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
const INF = Infinity;
let n;
let k;
let s;
function solve() {
    const a = af(n);
    for (let i = 0; i < n; i++) {
        a[i] = (s[i] == '1' ? 1 : 0);
    }
    // printf("n %d k %d s %s a %j\n", n, k, s, a);
    const K = k;
    const ans = af(n).fill(0);
    const keven = ((k % 2) == 0 ? true : false);
    for (let i = 0; i + 1 < n && k > 0; i++) {
        if (keven && a[i] == 0) {
            ans[i]++;
            k--;
        }
        else if (!keven && a[i] == 1) {
            ans[i]++;
            k--;
        }
    }
    ans[n - 1] = k;
    const b = af(n);
    for (let i = 0; i < n; i++) {
        b[i] = (a[i] + ans[i] + K) % 2;
        // printf("%d", (a[i] + ans[i] + K) % 2), ' ');
    }
    process.stdout.write(b.join(''));
    process.stdout.write('\n');
    process.stdout.write(ans.join(' '));
    process.stdout.write('\n');
}
function main() {
    let tc = nextInt();
    while (tc--) {
        n = nextInt();
        k = nextInt();
        s = nextStr();
        solve();
    }
}

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

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

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

const calc = (n, k, bits)=>{
    let usage = new Array(n).fill(0);
    let originalK = k;

    let flipped = 0;

    for (let i = 0; i < n; i++) {
        let flips = k % 2;
        let res = bits[i] ^ flipped ^ flips;
        if (!res && k) {
            k--;
            usage[i]++;
            flipped = 1 - flipped;
        }
    }
    usage[n - 1] += k;

    for (let i = 0; i < n; i++) {
        let flips = (originalK - usage[i]) % 2;
        bits[i] = bits[i] ^ flips;
    }

    return `${bits.join('')}\n${usage.join(' ')}`;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let [n, k] = ra();
        let bits = readline().split('').map(a=>+a);
        console.log(`${calc(n, k, bits)}`);
    }
}

const processData = (lines) => {
    let n = +lines[0]
    let cur = 0
    while(n--) {
        cur++
        let [_, k] = lines[cur].split(' ').map(x => +x)
        cur++
        let str = lines[cur].split('').map(x => +x)

        let xor = k%2;
        for (let i=0; i<str.length; i++) {
            str[i] = str[i]^xor;
        }
        let res = new Array(str.length);
        for (let i=0; i<res.length; i++) {
            res[i] = 0;
        }
        for (let i=0; i<str.length && k > 0; i++) {
            if (str[i] === 0) {
                k--;
                str[i] = 1;
                res[i] = 1;
            }
        }

        if (k) {
            if (k%2 === 0) {
                res[0] += k;
            } else {
                res[res.length-1] += k;
                str[str.length-1] ^= 1;;
            }
        }
        console.log(str.join(''));
        console.log(res.join(' '))
    }
}

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

const readline = require('readline')

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

function solve(n, k, str) {
    const ans = Array(n).fill(0)
    const final = str.split('')
    let used = 0
    for (let i = 0; i < str.length; i++) {
        const ch = str[i]
        let x
        // flip k - x
        if (ch === '1') {
            // k - x is even
            if (k & 1) {
                x = 1
            } else {
                x = 0
            }
        } else {
            // k - x is odd
            if (k & 1) {
                x = 0
            } else {
                x = 1
            }
        }
        //
        if (used >= k) x = 0
        if (i === n - 1) x = k - used
        ans[i] = x
        used += x
        //
        if ((k - x) & 1) {
            final[i] = ch === '1' ? '0' : '1'
        // } else {
        //     final = ch
        }
    }
    return final.join('') + '\n' + 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++];
}
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 solve = () => {
  let t = getValue();
  while (t--) {
    let [n, k] = iInpArr();
    let arr = iInpArr1();
    let res = new Array(n).fill(0);
    if (k % 2 === 1) {
      let flag = 0;
      for (let i = 0; i < n - 1; i++) {
        if (arr[i] === 0) arr[i] = 1;
        else if (arr[i] === 1 && flag === 0) {
          flag = 1;
        } else arr[i] = 0;
      }
      if (flag === 1) arr[n - 1] = arr[n - 1] === 0 ? 1 : 0;
      k--;
    }
    for (let i = 0; i < n; i++) {
      if (i === n - 1 && k > 0) {
        if (k % 2 !== 0) arr[i] = arr[i] === 0 ? 1 : 0;
        res[i] += k;
      } else if (arr[i] === 0 && k > 0) {
        arr[i] = 1;
        res[i]++;
        k--;
      }
    }
    console.log(arr.join(""));
    console.log(res.join(" "));
  }
};
solve();


You have two positive integers $$$a$$$ and $$$b$$$.You can perform two kinds of operations:  $$$a = \lfloor \frac{a}{b} \rfloor$$$ (replace $$$a$$$ with the integer part of the division between $$$a$$$ and $$$b$$$)  $$$b=b+1$$$ (increase $$$b$$$ by $$$1$$$) Find the minimum number of operations required to make $$$a=0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of the description of each test case contains two integers $$$a$$$, $$$b$$$ ($$$1 \le a,b \le 10^9$$$).

For each test case, print a single integer: the minimum number of operations required to make $$$a=0$$$.

NoteIn the first test case, one of the optimal solutions is:  Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 4$$$ and $$$b = 2$$$.  Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 2$$$.  Increase $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 3$$$.  Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 0$$$ and $$$b = 3$$$.

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function readInt() {
  return readline()|0
}

function readIntArr() {
  return readline().split(' ').map(x => x|0)
}

function main() {
  const N = readInt()
  for (let i = 0; i < N; ++i) {
    let total = 1
    let c = 0
    let [a, b] = readIntArr()
    if (b == 1) {
      b += 1
      c = 1
    }

    function found(a, b, total) {
      let fo = false
      for (let i = 0; i < total; i++) {
        if (((b + i) ** (total - i) > a)) {
          fo = true;
        }
      }
      return fo
    }

    while (!found(a, b, total)) {
      total += 1
    }
    console.log(total + 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++];
}

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

function main() {
    const x = readline();
    // 1 1 7
    // 6 9, 15, 18

    var answer = {}

    Array(Number(x)).fill(1).map((t, i) => {
        var [a, b] = readline().split(' ').map((x, i) => {
            // if (minA > Number(x)) minA = Number(x)
            return parseInt(x)
        })
        var min = 100000000
        var bb
        var aa
        if (a < b) return console.log(1)

        for (var i = 0; i < 1000; i++) {
            aa = a
            answer = i
            bb = b + i
            if (bb === 1) continue

            while (aa !== 0) {
                aa = Math.floor(aa / bb)
                answer += 1
            }
            // console.log(a,bb, answer)

            // console.log(min)
            min = Math.min(min, answer)
        }
        console.log(min)
        // console.log(Math.min(answer, answer2))

    })
}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

"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));
    if (k > n) console.log(1);
    else if (n === k) console.log(2);
    else {
      const red = (n, k) => {
        let cnt = 0;
        while (n > 0) {
          n = Math.floor(n / k);
          cnt++;
        }
        return cnt;
      };
      let cnt = 0;
      if (k === 1) {
        k++;
        cnt++;
      }
      let prev = red(n, k) + cnt;
      while (true) {
        k++;
        cnt++;
        let l = red(n, k) + cnt;
        if (prev < l) {
          console.log(prev);
          break;
        } else prev = l;
      }
    }
  }
};
solve();

//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 getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------

function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var A = nextInt();
		var B = nextInt();
		var add = 0;
		if(B == 1){
			add = 1;
			B++;
		}
		var now = B;
		var output = Math.pow(10, 15);
		while(true){
			var tmp = A;
			var count = now - B;
			while(tmp > 0){
				count++;
				tmp = Math.floor(tmp / now);
			}
			if(output >= count){
				output = count;
			}else{
				break;
			}
			now++;
		}
		myout(output + add);
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function readInt() {
  return readline()|0
}

function readIntArr() {
  return readline().split(' ').map(x => x|0)
}

function main() {
   const n = readInt();

   for(let i=0; i < n; i++) {
     let [a, b] = readIntArr();
     let phase = 1;
     if(b === 1) {
       phase = 2;
     }

     const func = () => {
       for(let i = 1; i <= phase; i++) {
         if (((b + phase) - i)**(i) > a) return false;
       }

       return true;
     }

     while (func()) {
      phase++;
     }

     console.log(phase);
   }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function readInt() {
  return readline()|0
}

function readIntArr() {
  return readline().split(' ').map(x => x|0)
}

function main() {
  const N = readInt()
  for (let i = 0; i < N; ++i) {
    let total = 1
    let c = 0
    let [a, b] = readIntArr()
    if (b == 1) {
      b += 1
      c = 1
    }
    while (b ** total <= a && (b + 1) ** (total - 1) <= a && (b + 2) ** (total - 2) <= a) {
      total += 1
    }
    console.log(total + c)
  }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function readInt() {
  return readline()|0
}

function readIntArr() {
  return readline().split(' ').map(x => x|0)
}

function main() {
  const N = readInt()
  for (let i = 0; i < N; ++i) {
    let total = 1
    let c = 0
    let [a, b] = readIntArr()
    if (b == 1) {
      b += 1
      c = 1
    }
    while (b ** total < a && (b + 1) ** (total - 1) < a && (b + 2) ** (total - 2) < a) {
      total += 1
    }
    console.log(total + 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++];
}

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

function main() {
    const x = readline();
    // 1 1 7
    // 6 9, 15, 18

    var answer = {}

    Array(Number(x)).fill(1).map((t, i) => {
        var [a, b] = readline().split(' ').map((x, i) => {
            // if (minA > Number(x)) minA = Number(x)
            return parseInt(x)
        })
        var min = 100000000
        var bb
        var aa
        if (a < b) return console.log(1)

        for (var i = 0; i < 5; i++) {
            aa = a
            answer = i
            bb = b + i
            if (bb === 1) continue

            while (aa !== 0) {
                aa = Math.floor(aa / bb)
                answer += 1
            }
            // console.log(a,bb, answer)

            // console.log(min)
            min = Math.min(min, answer)
        }
        console.log(min)
        // console.log(Math.min(answer, answer2))

    })
}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

'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();
    // 1 1 7
    // 6 9, 15, 18

    var answer = {}

    Array(Number(x)).fill(1).map((t, i) => {
        var [a, b] = readline().split(' ').map((x, i) => {
            // if (minA > Number(x)) minA = Number(x)
            return parseInt(x)
        })
        var answer = 0
        var answer2 = 0
        if (a < b) return console.log(1)
        if(b===1)  {
            answer = 1
            answer2 = 2
            b = 2
        }
        // console.log(b,a)

        var bb = b +1
        var aa = a
        while(a!==0){
            a=Math.floor(a/b)
            answer+=1
        }

        while(aa!==0){
            aa=Math.floor(aa/bb)
            answer2+=1
        }
        console.log(Math.min(answer, answer2))

    })
}

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
}

"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++];
}
let obj = {};
const precompute = () => {
  for (let i = 1; i <= 10000; i++) obj[i * i * i] = 1;
};
const solve = () => {
  let t = parseInt(readline());
  precompute();
  while (t--) {
    let [n, k] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (k > n) console.log(1);
    else {
      if (n === k) console.log(2);
      else {
        let cnt = 0;
        if (n % k === 0) {
          k += 2;
          cnt += 2;
        }
        while (n > 0) {
          cnt++;
          n = Math.floor(n / k);
        }
        console.log(cnt);
      }
    }
  }
};
solve();


You are a coach at your local university. There are $$$n$$$ students under your supervision, the programming skill of the $$$i$$$-th student is $$$a_i$$$.You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maximum number of students. But you also know that a team should be balanced. It means that the programming skill of each pair of students in a created team should differ by no more than $$$5$$$.Your task is to report the maximum possible number of students in a balanced team.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is a programming skill of the $$$i$$$-th student.

Print one integer — the maximum possible number of students in a balanced team.

NoteIn the first example you can create a team with skills $$$[12, 17, 15]$$$.In the second example you can take all students in a team because their programming skills are equal.In the third example you can create a team consisting of a single student (and you cannot create a team consisting of at least two students).

var a = readline();
var skills = readline().split(' ');
var sortedSkills = skills.sort((a,b) => a-b);
var differences = [];

for (var i=0; i<skills.length-1; i++) {
    differences[i] = sortedSkills[i+1] - sortedSkills[i];
}

var maxAmount = 1;
var currentAmount = 1;
var currentDiff = 0;
var lowerBoundary = 0;
for (var j=0; j<differences.length; j++) {
    currentDiff += differences[j];
    if (currentDiff<=5) {
        currentAmount++;
    } else {
        maxAmount = maxAmount < currentAmount ? currentAmount : maxAmount;
        currentAmount++;
        while (currentDiff > 5) {
            currentDiff -= differences[lowerBoundary];
            lowerBoundary++;
            currentAmount--;
        }
    }
}
maxAmount = maxAmount < currentAmount ? currentAmount : maxAmount;

print(maxAmount);


Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".

NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

'use strict';

var readline = require('readline');

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

function __extends(d, b) {
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isFunction(x) {
    return typeof x === 'function';
}
//# sourceMappingURL=isFunction.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var _enable_super_gross_mode_that_will_cause_bad_things = false;
var config = {
    Promise: undefined,
    set useDeprecatedSynchronousErrorHandling(value) {
        if (value) {
            var error = /*@__PURE__*/ new Error();
            /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
        }
        _enable_super_gross_mode_that_will_cause_bad_things = value;
    },
    get useDeprecatedSynchronousErrorHandling() {
        return _enable_super_gross_mode_that_will_cause_bad_things;
    },
};
//# sourceMappingURL=config.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function hostReportError(err) {
    setTimeout(function () { throw err; }, 0);
}
//# sourceMappingURL=hostReportError.js.map

/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */
var empty = {
    closed: true,
    next: function (value) { },
    error: function (err) {
        if (config.useDeprecatedSynchronousErrorHandling) {
            throw err;
        }
        else {
            hostReportError(err);
        }
    },
    complete: function () { }
};
//# sourceMappingURL=Observer.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();
//# sourceMappingURL=isArray.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isObject(x) {
    return x !== null && typeof x === 'object';
}
//# sourceMappingURL=isObject.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () {
    function UnsubscriptionErrorImpl(errors) {
        Error.call(this);
        this.message = errors ?
            errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n  ') : '';
        this.name = 'UnsubscriptionError';
        this.errors = errors;
        return this;
    }
    UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);
    return UnsubscriptionErrorImpl;
})();
var UnsubscriptionError = UnsubscriptionErrorImpl;
//# sourceMappingURL=UnsubscriptionError.js.map

/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */
var Subscription = /*@__PURE__*/ (function () {
    function Subscription(unsubscribe) {
        this.closed = false;
        this._parentOrParents = null;
        this._subscriptions = null;
        if (unsubscribe) {
            this._unsubscribe = unsubscribe;
        }
    }
    Subscription.prototype.unsubscribe = function () {
        var errors;
        if (this.closed) {
            return;
        }
        var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
        this.closed = true;
        this._parentOrParents = null;
        this._subscriptions = null;
        if (_parentOrParents instanceof Subscription) {
            _parentOrParents.remove(this);
        }
        else if (_parentOrParents !== null) {
            for (var index = 0; index < _parentOrParents.length; ++index) {
                var parent_1 = _parentOrParents[index];
                parent_1.remove(this);
            }
        }
        if (isFunction(_unsubscribe)) {
            try {
                _unsubscribe.call(this);
            }
            catch (e) {
                errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];
            }
        }
        if (isArray(_subscriptions)) {
            var index = -1;
            var len = _subscriptions.length;
            while (++index < len) {
                var sub = _subscriptions[index];
                if (isObject(sub)) {
                    try {
                        sub.unsubscribe();
                    }
                    catch (e) {
                        errors = errors || [];
                        if (e instanceof UnsubscriptionError) {
                            errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
                        }
                        else {
                            errors.push(e);
                        }
                    }
                }
            }
        }
        if (errors) {
            throw new UnsubscriptionError(errors);
        }
    };
    Subscription.prototype.add = function (teardown) {
        var subscription = teardown;
        if (!teardown) {
            return Subscription.EMPTY;
        }
        switch (typeof teardown) {
            case 'function':
                subscription = new Subscription(teardown);
            case 'object':
                if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
                    return subscription;
                }
                else if (this.closed) {
                    subscription.unsubscribe();
                    return subscription;
                }
                else if (!(subscription instanceof Subscription)) {
                    var tmp = subscription;
                    subscription = new Subscription();
                    subscription._subscriptions = [tmp];
                }
                break;
            default: {
                throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
            }
        }
        var _parentOrParents = subscription._parentOrParents;
        if (_parentOrParents === null) {
            subscription._parentOrParents = this;
        }
        else if (_parentOrParents instanceof Subscription) {
            if (_parentOrParents === this) {
                return subscription;
            }
            subscription._parentOrParents = [_parentOrParents, this];
        }
        else if (_parentOrParents.indexOf(this) === -1) {
            _parentOrParents.push(this);
        }
        else {
            return subscription;
        }
        var subscriptions = this._subscriptions;
        if (subscriptions === null) {
            this._subscriptions = [subscription];
        }
        else {
            subscriptions.push(subscription);
        }
        return subscription;
    };
    Subscription.prototype.remove = function (subscription) {
        var subscriptions = this._subscriptions;
        if (subscriptions) {
            var subscriptionIndex = subscriptions.indexOf(subscription);
            if (subscriptionIndex !== -1) {
                subscriptions.splice(subscriptionIndex, 1);
            }
        }
    };
    Subscription.EMPTY = (function (empty) {
        empty.closed = true;
        return empty;
    }(new Subscription()));
    return Subscription;
}());
function flattenUnsubscriptionErrors(errors) {
    return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);
}
//# sourceMappingURL=Subscription.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var rxSubscriber = /*@__PURE__*/ (function () {
    return typeof Symbol === 'function'
        ? /*@__PURE__*/ Symbol('rxSubscriber')
        : '@@rxSubscriber_' + /*@__PURE__*/ Math.random();
})();
//# sourceMappingURL=rxSubscriber.js.map

/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */
var Subscriber = /*@__PURE__*/ (function (_super) {
    __extends(Subscriber, _super);
    function Subscriber(destinationOrNext, error, complete) {
        var _this = _super.call(this) || this;
        _this.syncErrorValue = null;
        _this.syncErrorThrown = false;
        _this.syncErrorThrowable = false;
        _this.isStopped = false;
        switch (arguments.length) {
            case 0:
                _this.destination = empty;
                break;
            case 1:
                if (!destinationOrNext) {
                    _this.destination = empty;
                    break;
                }
                if (typeof destinationOrNext === 'object') {
                    if (destinationOrNext instanceof Subscriber) {
                        _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
                        _this.destination = destinationOrNext;
                        destinationOrNext.add(_this);
                    }
                    else {
                        _this.syncErrorThrowable = true;
                        _this.destination = new SafeSubscriber(_this, destinationOrNext);
                    }
                    break;
                }
            default:
                _this.syncErrorThrowable = true;
                _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);
                break;
        }
        return _this;
    }
    Subscriber.prototype[rxSubscriber] = function () { return this; };
    Subscriber.create = function (next, error, complete) {
        var subscriber = new Subscriber(next, error, complete);
        subscriber.syncErrorThrowable = false;
        return subscriber;
    };
    Subscriber.prototype.next = function (value) {
        if (!this.isStopped) {
            this._next(value);
        }
    };
    Subscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            this.isStopped = true;
            this._error(err);
        }
    };
    Subscriber.prototype.complete = function () {
        if (!this.isStopped) {
            this.isStopped = true;
            this._complete();
        }
    };
    Subscriber.prototype.unsubscribe = function () {
        if (this.closed) {
            return;
        }
        this.isStopped = true;
        _super.prototype.unsubscribe.call(this);
    };
    Subscriber.prototype._next = function (value) {
        this.destination.next(value);
    };
    Subscriber.prototype._error = function (err) {
        this.destination.error(err);
        this.unsubscribe();
    };
    Subscriber.prototype._complete = function () {
        this.destination.complete();
        this.unsubscribe();
    };
    Subscriber.prototype._unsubscribeAndRecycle = function () {
        var _parentOrParents = this._parentOrParents;
        this._parentOrParents = null;
        this.unsubscribe();
        this.closed = false;
        this.isStopped = false;
        this._parentOrParents = _parentOrParents;
        return this;
    };
    return Subscriber;
}(Subscription));
var SafeSubscriber = /*@__PURE__*/ (function (_super) {
    __extends(SafeSubscriber, _super);
    function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
        var _this = _super.call(this) || this;
        _this._parentSubscriber = _parentSubscriber;
        var next;
        var context = _this;
        if (isFunction(observerOrNext)) {
            next = observerOrNext;
        }
        else if (observerOrNext) {
            next = observerOrNext.next;
            error = observerOrNext.error;
            complete = observerOrNext.complete;
            if (observerOrNext !== empty) {
                context = Object.create(observerOrNext);
                if (isFunction(context.unsubscribe)) {
                    _this.add(context.unsubscribe.bind(context));
                }
                context.unsubscribe = _this.unsubscribe.bind(_this);
            }
        }
        _this._context = context;
        _this._next = next;
        _this._error = error;
        _this._complete = complete;
        return _this;
    }
    SafeSubscriber.prototype.next = function (value) {
        if (!this.isStopped && this._next) {
            var _parentSubscriber = this._parentSubscriber;
            if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                this.__tryOrUnsub(this._next, value);
            }
            else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            var _parentSubscriber = this._parentSubscriber;
            var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;
            if (this._error) {
                if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(this._error, err);
                    this.unsubscribe();
                }
                else {
                    this.__tryOrSetError(_parentSubscriber, this._error, err);
                    this.unsubscribe();
                }
            }
            else if (!_parentSubscriber.syncErrorThrowable) {
                this.unsubscribe();
                if (useDeprecatedSynchronousErrorHandling) {
                    throw err;
                }
                hostReportError(err);
            }
            else {
                if (useDeprecatedSynchronousErrorHandling) {
                    _parentSubscriber.syncErrorValue = err;
                    _parentSubscriber.syncErrorThrown = true;
                }
                else {
                    hostReportError(err);
                }
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.complete = function () {
        var _this = this;
        if (!this.isStopped) {
            var _parentSubscriber = this._parentSubscriber;
            if (this._complete) {
                var wrappedComplete = function () { return _this._complete.call(_this._context); };
                if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(wrappedComplete);
                    this.unsubscribe();
                }
                else {
                    this.__tryOrSetError(_parentSubscriber, wrappedComplete);
                    this.unsubscribe();
                }
            }
            else {
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            this.unsubscribe();
            if (config.useDeprecatedSynchronousErrorHandling) {
                throw err;
            }
            else {
                hostReportError(err);
            }
        }
    };
    SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
        if (!config.useDeprecatedSynchronousErrorHandling) {
            throw new Error('bad call');
        }
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            if (config.useDeprecatedSynchronousErrorHandling) {
                parent.syncErrorValue = err;
                parent.syncErrorThrown = true;
                return true;
            }
            else {
                hostReportError(err);
                return true;
            }
        }
        return false;
    };
    SafeSubscriber.prototype._unsubscribe = function () {
        var _parentSubscriber = this._parentSubscriber;
        this._context = null;
        this._parentSubscriber = null;
        _parentSubscriber.unsubscribe();
    };
    return SafeSubscriber;
}(Subscriber));
//# sourceMappingURL=Subscriber.js.map

/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */
function canReportError(observer) {
    while (observer) {
        var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;
        if (closed_1 || isStopped) {
            return false;
        }
        else if (destination && destination instanceof Subscriber) {
            observer = destination;
        }
        else {
            observer = null;
        }
    }
    return true;
}
//# sourceMappingURL=canReportError.js.map

/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */
function toSubscriber(nextOrObserver, error, complete) {
    if (nextOrObserver) {
        if (nextOrObserver instanceof Subscriber) {
            return nextOrObserver;
        }
        if (nextOrObserver[rxSubscriber]) {
            return nextOrObserver[rxSubscriber]();
        }
    }
    if (!nextOrObserver && !error && !complete) {
        return new Subscriber(empty);
    }
    return new Subscriber(nextOrObserver, error, complete);
}
//# sourceMappingURL=toSubscriber.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })();
//# sourceMappingURL=observable.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function noop() { }
//# sourceMappingURL=noop.js.map

/** PURE_IMPORTS_START _noop PURE_IMPORTS_END */
function pipeFromArray(fns) {
    if (!fns) {
        return noop;
    }
    if (fns.length === 1) {
        return fns[0];
    }
    return function piped(input) {
        return fns.reduce(function (prev, fn) { return fn(prev); }, input);
    };
}
//# sourceMappingURL=pipe.js.map

/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */
var Observable = /*@__PURE__*/ (function () {
    function Observable(subscribe) {
        this._isScalar = false;
        if (subscribe) {
            this._subscribe = subscribe;
        }
    }
    Observable.prototype.lift = function (operator) {
        var observable = new Observable();
        observable.source = this;
        observable.operator = operator;
        return observable;
    };
    Observable.prototype.subscribe = function (observerOrNext, error, complete) {
        var operator = this.operator;
        var sink = toSubscriber(observerOrNext, error, complete);
        if (operator) {
            sink.add(operator.call(sink, this.source));
        }
        else {
            sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
                this._subscribe(sink) :
                this._trySubscribe(sink));
        }
        if (config.useDeprecatedSynchronousErrorHandling) {
            if (sink.syncErrorThrowable) {
                sink.syncErrorThrowable = false;
                if (sink.syncErrorThrown) {
                    throw sink.syncErrorValue;
                }
            }
        }
        return sink;
    };
    Observable.prototype._trySubscribe = function (sink) {
        try {
            return this._subscribe(sink);
        }
        catch (err) {
            if (config.useDeprecatedSynchronousErrorHandling) {
                sink.syncErrorThrown = true;
                sink.syncErrorValue = err;
            }
            if (canReportError(sink)) {
                sink.error(err);
            }
            else {
                console.warn(err);
            }
        }
    };
    Observable.prototype.forEach = function (next, promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var subscription;
            subscription = _this.subscribe(function (value) {
                try {
                    next(value);
                }
                catch (err) {
                    reject(err);
                    if (subscription) {
                        subscription.unsubscribe();
                    }
                }
            }, reject, resolve);
        });
    };
    Observable.prototype._subscribe = function (subscriber) {
        var source = this.source;
        return source && source.subscribe(subscriber);
    };
    Observable.prototype[observable] = function () {
        return this;
    };
    Observable.prototype.pipe = function () {
        var operations = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            operations[_i] = arguments[_i];
        }
        if (operations.length === 0) {
            return this;
        }
        return pipeFromArray(operations)(this);
    };
    Observable.prototype.toPromise = function (promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var value;
            _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
        });
    };
    Observable.create = function (subscribe) {
        return new Observable(subscribe);
    };
    return Observable;
}());
function getPromiseCtor(promiseCtor) {
    if (!promiseCtor) {
        promiseCtor =  Promise;
    }
    if (!promiseCtor) {
        throw new Error('no Promise impl found');
    }
    return promiseCtor;
}
//# sourceMappingURL=Observable.js.map

function tnLineStdinReader() {
  return new Observable(subscribe => {
    const stdin = readline.createInterface(process.stdin);
    let tests = null;
    let n = null;
    stdin.on('line', line => {
      if (tests === null) {
        tests = +line;
      } else if (n === null) {
        n = +line;
        tests--;
      } else {
        n = null;
        subscribe.next(line);

        if (tests === 0) {
          stdin.close();
          subscribe.complete();
        }
      }
    });
  });
}

function isHappy(arr) {
  if (arr[0] <= 0 || arr[arr.length - 1] <= 0) {
    return 'NO';
  }

  let sum = 0;

  for (let x = 0; x < arr.length - 1; x++) {
    sum += arr[x];

    if (sum <= 0) {
      return 'NO';
    }
  }

  sum = 0;

  for (let x = arr.length - 1; x > 0; x--) {
    sum += arr[x];

    if (sum <= 0) {
      return 'NO';
    }
  }

  return 'YES';
}

tnLineStdinReader().subscribe(input => {
  const arr = input.split(' ').map(i => +i);
  console.log(isHappy(arr));
});

'use strict'

let t = parseInt(readline())

function calc (arr) {
    let max_so_far = Number.MIN_SAFE_INTEGER
    let max_here = 0

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

        if (max_here < 0) {
            max_here = 0
        }

        if (max_so_far < max_here) {
            max_so_far = max_here
        }
    }
    return max_so_far
}

while (t --> 0) {
    const n = readline()
    const arr = readline().split(' ').map(function(x) {
        return parseInt(x)
    })

    let whole = 0
    for (let i in arr) whole += arr[i]

    let a = calc(arr)
    let b = calc(arr.reverse())

    let mx = Math.max(a, b)
    let ok = whole > mx

    print(ok ? 'YES': 'NO')
}

var numRun= readline();

for(var n=0;n<numRun;n++){
    var k=readline();
    var arr=readline().split(" ").map(function(x){return parseInt(x);});

    var prefix=0;
    var suffix=0;
    var no=false;
    for(var i=0;i<arr.length;i++){
        prefix+=arr[i];
        if(prefix<=0){print("NO");no=true;break;}

        suffix+=arr[arr.length-1-i];
        if(suffix<=0){print("NO");no=true;break;}
    }
    if(!no){print("YES");}
}//num runs

// 'use strict';

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

// let inputString = '';
// let currentLine = 0;

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

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

//   main();
// });

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

// function print(item) {
//   console.log(item);
// }

function maxSubArraySum(array_of_numbers, init_value, array_size) {
  var max_so_far = Number.MIN_SAFE_INTEGER;
  var max_ending_here = 0;
  var start_index = 0;
  var end_index = 0;
  var start_tmp = 0;

  for (var i = init_value; i < array_size; i++) {
    max_ending_here += array_of_numbers[i];

    if (max_so_far < max_ending_here) {
      max_so_far = max_ending_here;
      start_index = start_tmp;
      end_index = i;
    }

    if (max_ending_here < 0) {
      max_ending_here = 0;
      start_tmp = i + 1;
    }
  }
  return { max_so_far, start_index, end_index };
}

function main() {
  const test_cases = parseInt(readline(), 10);
  for(var i = 0; i < test_cases; i++) {
    var cupcakes_count = parseInt(readline(), 10);
    var cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));

    var total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);

    var result_begin = maxSubArraySum(cupcakes_taste, 0, cupcakes_count - 1);
    var result_end = maxSubArraySum(cupcakes_taste, 1, cupcakes_count);

    if (total_taste > Math.max(result_begin.max_so_far, result_end.max_so_far)) {
      print('YES');
    } else {
      print('NO');
    }
  }
}

main();

'use strict';

var readline = require('readline');

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

function __extends(d, b) {
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isFunction(x) {
    return typeof x === 'function';
}
//# sourceMappingURL=isFunction.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var _enable_super_gross_mode_that_will_cause_bad_things = false;
var config = {
    Promise: undefined,
    set useDeprecatedSynchronousErrorHandling(value) {
        if (value) {
            var error = /*@__PURE__*/ new Error();
            /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
        }
        _enable_super_gross_mode_that_will_cause_bad_things = value;
    },
    get useDeprecatedSynchronousErrorHandling() {
        return _enable_super_gross_mode_that_will_cause_bad_things;
    },
};
//# sourceMappingURL=config.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function hostReportError(err) {
    setTimeout(function () { throw err; }, 0);
}
//# sourceMappingURL=hostReportError.js.map

/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */
var empty = {
    closed: true,
    next: function (value) { },
    error: function (err) {
        if (config.useDeprecatedSynchronousErrorHandling) {
            throw err;
        }
        else {
            hostReportError(err);
        }
    },
    complete: function () { }
};
//# sourceMappingURL=Observer.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();
//# sourceMappingURL=isArray.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isObject(x) {
    return x !== null && typeof x === 'object';
}
//# sourceMappingURL=isObject.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () {
    function UnsubscriptionErrorImpl(errors) {
        Error.call(this);
        this.message = errors ?
            errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n  ') : '';
        this.name = 'UnsubscriptionError';
        this.errors = errors;
        return this;
    }
    UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);
    return UnsubscriptionErrorImpl;
})();
var UnsubscriptionError = UnsubscriptionErrorImpl;
//# sourceMappingURL=UnsubscriptionError.js.map

/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */
var Subscription = /*@__PURE__*/ (function () {
    function Subscription(unsubscribe) {
        this.closed = false;
        this._parentOrParents = null;
        this._subscriptions = null;
        if (unsubscribe) {
            this._unsubscribe = unsubscribe;
        }
    }
    Subscription.prototype.unsubscribe = function () {
        var errors;
        if (this.closed) {
            return;
        }
        var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
        this.closed = true;
        this._parentOrParents = null;
        this._subscriptions = null;
        if (_parentOrParents instanceof Subscription) {
            _parentOrParents.remove(this);
        }
        else if (_parentOrParents !== null) {
            for (var index = 0; index < _parentOrParents.length; ++index) {
                var parent_1 = _parentOrParents[index];
                parent_1.remove(this);
            }
        }
        if (isFunction(_unsubscribe)) {
            try {
                _unsubscribe.call(this);
            }
            catch (e) {
                errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];
            }
        }
        if (isArray(_subscriptions)) {
            var index = -1;
            var len = _subscriptions.length;
            while (++index < len) {
                var sub = _subscriptions[index];
                if (isObject(sub)) {
                    try {
                        sub.unsubscribe();
                    }
                    catch (e) {
                        errors = errors || [];
                        if (e instanceof UnsubscriptionError) {
                            errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
                        }
                        else {
                            errors.push(e);
                        }
                    }
                }
            }
        }
        if (errors) {
            throw new UnsubscriptionError(errors);
        }
    };
    Subscription.prototype.add = function (teardown) {
        var subscription = teardown;
        if (!teardown) {
            return Subscription.EMPTY;
        }
        switch (typeof teardown) {
            case 'function':
                subscription = new Subscription(teardown);
            case 'object':
                if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
                    return subscription;
                }
                else if (this.closed) {
                    subscription.unsubscribe();
                    return subscription;
                }
                else if (!(subscription instanceof Subscription)) {
                    var tmp = subscription;
                    subscription = new Subscription();
                    subscription._subscriptions = [tmp];
                }
                break;
            default: {
                throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
            }
        }
        var _parentOrParents = subscription._parentOrParents;
        if (_parentOrParents === null) {
            subscription._parentOrParents = this;
        }
        else if (_parentOrParents instanceof Subscription) {
            if (_parentOrParents === this) {
                return subscription;
            }
            subscription._parentOrParents = [_parentOrParents, this];
        }
        else if (_parentOrParents.indexOf(this) === -1) {
            _parentOrParents.push(this);
        }
        else {
            return subscription;
        }
        var subscriptions = this._subscriptions;
        if (subscriptions === null) {
            this._subscriptions = [subscription];
        }
        else {
            subscriptions.push(subscription);
        }
        return subscription;
    };
    Subscription.prototype.remove = function (subscription) {
        var subscriptions = this._subscriptions;
        if (subscriptions) {
            var subscriptionIndex = subscriptions.indexOf(subscription);
            if (subscriptionIndex !== -1) {
                subscriptions.splice(subscriptionIndex, 1);
            }
        }
    };
    Subscription.EMPTY = (function (empty) {
        empty.closed = true;
        return empty;
    }(new Subscription()));
    return Subscription;
}());
function flattenUnsubscriptionErrors(errors) {
    return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);
}
//# sourceMappingURL=Subscription.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var rxSubscriber = /*@__PURE__*/ (function () {
    return typeof Symbol === 'function'
        ? /*@__PURE__*/ Symbol('rxSubscriber')
        : '@@rxSubscriber_' + /*@__PURE__*/ Math.random();
})();
//# sourceMappingURL=rxSubscriber.js.map

/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */
var Subscriber = /*@__PURE__*/ (function (_super) {
    __extends(Subscriber, _super);
    function Subscriber(destinationOrNext, error, complete) {
        var _this = _super.call(this) || this;
        _this.syncErrorValue = null;
        _this.syncErrorThrown = false;
        _this.syncErrorThrowable = false;
        _this.isStopped = false;
        switch (arguments.length) {
            case 0:
                _this.destination = empty;
                break;
            case 1:
                if (!destinationOrNext) {
                    _this.destination = empty;
                    break;
                }
                if (typeof destinationOrNext === 'object') {
                    if (destinationOrNext instanceof Subscriber) {
                        _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
                        _this.destination = destinationOrNext;
                        destinationOrNext.add(_this);
                    }
                    else {
                        _this.syncErrorThrowable = true;
                        _this.destination = new SafeSubscriber(_this, destinationOrNext);
                    }
                    break;
                }
            default:
                _this.syncErrorThrowable = true;
                _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);
                break;
        }
        return _this;
    }
    Subscriber.prototype[rxSubscriber] = function () { return this; };
    Subscriber.create = function (next, error, complete) {
        var subscriber = new Subscriber(next, error, complete);
        subscriber.syncErrorThrowable = false;
        return subscriber;
    };
    Subscriber.prototype.next = function (value) {
        if (!this.isStopped) {
            this._next(value);
        }
    };
    Subscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            this.isStopped = true;
            this._error(err);
        }
    };
    Subscriber.prototype.complete = function () {
        if (!this.isStopped) {
            this.isStopped = true;
            this._complete();
        }
    };
    Subscriber.prototype.unsubscribe = function () {
        if (this.closed) {
            return;
        }
        this.isStopped = true;
        _super.prototype.unsubscribe.call(this);
    };
    Subscriber.prototype._next = function (value) {
        this.destination.next(value);
    };
    Subscriber.prototype._error = function (err) {
        this.destination.error(err);
        this.unsubscribe();
    };
    Subscriber.prototype._complete = function () {
        this.destination.complete();
        this.unsubscribe();
    };
    Subscriber.prototype._unsubscribeAndRecycle = function () {
        var _parentOrParents = this._parentOrParents;
        this._parentOrParents = null;
        this.unsubscribe();
        this.closed = false;
        this.isStopped = false;
        this._parentOrParents = _parentOrParents;
        return this;
    };
    return Subscriber;
}(Subscription));
var SafeSubscriber = /*@__PURE__*/ (function (_super) {
    __extends(SafeSubscriber, _super);
    function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
        var _this = _super.call(this) || this;
        _this._parentSubscriber = _parentSubscriber;
        var next;
        var context = _this;
        if (isFunction(observerOrNext)) {
            next = observerOrNext;
        }
        else if (observerOrNext) {
            next = observerOrNext.next;
            error = observerOrNext.error;
            complete = observerOrNext.complete;
            if (observerOrNext !== empty) {
                context = Object.create(observerOrNext);
                if (isFunction(context.unsubscribe)) {
                    _this.add(context.unsubscribe.bind(context));
                }
                context.unsubscribe = _this.unsubscribe.bind(_this);
            }
        }
        _this._context = context;
        _this._next = next;
        _this._error = error;
        _this._complete = complete;
        return _this;
    }
    SafeSubscriber.prototype.next = function (value) {
        if (!this.isStopped && this._next) {
            var _parentSubscriber = this._parentSubscriber;
            if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                this.__tryOrUnsub(this._next, value);
            }
            else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            var _parentSubscriber = this._parentSubscriber;
            var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;
            if (this._error) {
                if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(this._error, err);
                    this.unsubscribe();
                }
                else {
                    this.__tryOrSetError(_parentSubscriber, this._error, err);
                    this.unsubscribe();
                }
            }
            else if (!_parentSubscriber.syncErrorThrowable) {
                this.unsubscribe();
                if (useDeprecatedSynchronousErrorHandling) {
                    throw err;
                }
                hostReportError(err);
            }
            else {
                if (useDeprecatedSynchronousErrorHandling) {
                    _parentSubscriber.syncErrorValue = err;
                    _parentSubscriber.syncErrorThrown = true;
                }
                else {
                    hostReportError(err);
                }
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.complete = function () {
        var _this = this;
        if (!this.isStopped) {
            var _parentSubscriber = this._parentSubscriber;
            if (this._complete) {
                var wrappedComplete = function () { return _this._complete.call(_this._context); };
                if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(wrappedComplete);
                    this.unsubscribe();
                }
                else {
                    this.__tryOrSetError(_parentSubscriber, wrappedComplete);
                    this.unsubscribe();
                }
            }
            else {
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            this.unsubscribe();
            if (config.useDeprecatedSynchronousErrorHandling) {
                throw err;
            }
            else {
                hostReportError(err);
            }
        }
    };
    SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
        if (!config.useDeprecatedSynchronousErrorHandling) {
            throw new Error('bad call');
        }
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            if (config.useDeprecatedSynchronousErrorHandling) {
                parent.syncErrorValue = err;
                parent.syncErrorThrown = true;
                return true;
            }
            else {
                hostReportError(err);
                return true;
            }
        }
        return false;
    };
    SafeSubscriber.prototype._unsubscribe = function () {
        var _parentSubscriber = this._parentSubscriber;
        this._context = null;
        this._parentSubscriber = null;
        _parentSubscriber.unsubscribe();
    };
    return SafeSubscriber;
}(Subscriber));
//# sourceMappingURL=Subscriber.js.map

/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */
function canReportError(observer) {
    while (observer) {
        var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;
        if (closed_1 || isStopped) {
            return false;
        }
        else if (destination && destination instanceof Subscriber) {
            observer = destination;
        }
        else {
            observer = null;
        }
    }
    return true;
}
//# sourceMappingURL=canReportError.js.map

/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */
function toSubscriber(nextOrObserver, error, complete) {
    if (nextOrObserver) {
        if (nextOrObserver instanceof Subscriber) {
            return nextOrObserver;
        }
        if (nextOrObserver[rxSubscriber]) {
            return nextOrObserver[rxSubscriber]();
        }
    }
    if (!nextOrObserver && !error && !complete) {
        return new Subscriber(empty);
    }
    return new Subscriber(nextOrObserver, error, complete);
}
//# sourceMappingURL=toSubscriber.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })();
//# sourceMappingURL=observable.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function noop() { }
//# sourceMappingURL=noop.js.map

/** PURE_IMPORTS_START _noop PURE_IMPORTS_END */
function pipeFromArray(fns) {
    if (!fns) {
        return noop;
    }
    if (fns.length === 1) {
        return fns[0];
    }
    return function piped(input) {
        return fns.reduce(function (prev, fn) { return fn(prev); }, input);
    };
}
//# sourceMappingURL=pipe.js.map

/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */
var Observable = /*@__PURE__*/ (function () {
    function Observable(subscribe) {
        this._isScalar = false;
        if (subscribe) {
            this._subscribe = subscribe;
        }
    }
    Observable.prototype.lift = function (operator) {
        var observable = new Observable();
        observable.source = this;
        observable.operator = operator;
        return observable;
    };
    Observable.prototype.subscribe = function (observerOrNext, error, complete) {
        var operator = this.operator;
        var sink = toSubscriber(observerOrNext, error, complete);
        if (operator) {
            sink.add(operator.call(sink, this.source));
        }
        else {
            sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
                this._subscribe(sink) :
                this._trySubscribe(sink));
        }
        if (config.useDeprecatedSynchronousErrorHandling) {
            if (sink.syncErrorThrowable) {
                sink.syncErrorThrowable = false;
                if (sink.syncErrorThrown) {
                    throw sink.syncErrorValue;
                }
            }
        }
        return sink;
    };
    Observable.prototype._trySubscribe = function (sink) {
        try {
            return this._subscribe(sink);
        }
        catch (err) {
            if (config.useDeprecatedSynchronousErrorHandling) {
                sink.syncErrorThrown = true;
                sink.syncErrorValue = err;
            }
            if (canReportError(sink)) {
                sink.error(err);
            }
            else {
                console.warn(err);
            }
        }
    };
    Observable.prototype.forEach = function (next, promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var subscription;
            subscription = _this.subscribe(function (value) {
                try {
                    next(value);
                }
                catch (err) {
                    reject(err);
                    if (subscription) {
                        subscription.unsubscribe();
                    }
                }
            }, reject, resolve);
        });
    };
    Observable.prototype._subscribe = function (subscriber) {
        var source = this.source;
        return source && source.subscribe(subscriber);
    };
    Observable.prototype[observable] = function () {
        return this;
    };
    Observable.prototype.pipe = function () {
        var operations = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            operations[_i] = arguments[_i];
        }
        if (operations.length === 0) {
            return this;
        }
        return pipeFromArray(operations)(this);
    };
    Observable.prototype.toPromise = function (promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var value;
            _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
        });
    };
    Observable.create = function (subscribe) {
        return new Observable(subscribe);
    };
    return Observable;
}());
function getPromiseCtor(promiseCtor) {
    if (!promiseCtor) {
        promiseCtor =  Promise;
    }
    if (!promiseCtor) {
        throw new Error('no Promise impl found');
    }
    return promiseCtor;
}
//# sourceMappingURL=Observable.js.map

function tnLineStdinReader() {
  return new Observable(function (subscribe) {
    var stdin = readline.createInterface(process.stdin);
    var tests = null;
    var n = null;
    stdin.on('line', function (line) {
      if (tests === null) {
        tests = +line;
      } else if (n === null) {
        n = +line;
        tests--;
      } else {
        n = null;
        subscribe.next(line);

        if (tests === 0) {
          stdin.close();
          subscribe.complete();
        }
      }
    });
  });
}

function isHappy(arr) {
  if (arr[0] <= 0 || arr[arr.length - 1] <= 0) {
    return 'NO';
  }

  var sum = 0;

  for (var x = 0; x < arr.length - 2; x++) {
    sum += arr[x];

    if (sum <= 0) {
      return 'NO';
    }
  }

  sum = 0;

  for (var _x = arr.length - 1; _x > 0; _x--) {
    sum += arr[_x];

    if (sum <= 0) {
      return 'NO';
    }
  }

  return 'YES';
}

tnLineStdinReader().subscribe(function (input) {
  var arr = input.split(' ').map(function (i) {
    return +i;
  });
  console.log(isHappy(arr));
});

'use strict'

let t = parseInt(readline())
while (t --> 0) {
    const n = parseInt(readline())
    const arr = readline().split(' ').map(function(x) {
        return parseInt(x)
    })

    let max_so_far = Number.MIN_SAFE_INTEGER
    let max_here = 0
    let neg = false

    for (let i = 0; i < n; ++i) {
        if (arr[i] < 0) neg = true
        max_here += arr[i]

        if (max_here < 0) {
            max_here = 0
        }

        if (max_so_far < max_here) {
            max_so_far = max_here
        }
    }

    let ok = false
    if (max_so_far < max_here) {
        ok = true
    } else if (max_so_far == max_here) {
        if (!neg) ok = true
    }

    print(ok ? 'YES': 'NO')
}

var numRun= readline();

for(var n=0;n<numRun;n++){
    var k=readline();
    var arr=readline().split(" ");

    var tot=0;
    var seg=0;
    var maxSeg=0;
    var totCt=0;
    var segCt=0;

    //print(arr);

    for(var i=0;i<arr.length;i++){
        var num=parseInt(arr[i],10);
        tot+=num; totCt++;
        if(seg+num<=0){seg=0;segCt=0;}//go below zero by adding this number, start a new segment
        else{seg+=num;segCt++;if(maxSeg<seg){maxSeg=seg;}}
        //if(num>0){seg+=num; if(maxSeg<seg){maxSeg=seg;}}
        //if(num<0){noNeg=true; seg=0;}//segment will not be all numbers
    }

    //print("tot: "+tot)
    //print("max seg: "+maxSeg)

    if(tot>maxSeg||(segCt==totCt&&tot==maxSeg)){print("YES");}
    else{print("NO");}

}//num runs

var numRun= readline();

for(var n=0;n<numRun;n++){
    var k=readline();
    var arr=readline().split(" ").map(function(x){return parseInt(x);});

    var tot=0;
    var seg=0;
    var maxSeg=0;
    var totCt=0;
    var segCt=0;

    //print(arr);

    for(var i=0;i<arr.length;i++){
        //var num=parseInt(arr[i],10);
        var num=arr[i];
        tot+=num; totCt++;
        if(seg+num<=0){seg=0;segCt=0;}//go below zero by adding this number, start a new segment
        else{seg+=num;segCt++;if(seg>maxSeg){maxSeg=seg;}}
        //if(num>0){seg+=num; if(maxSeg<seg){maxSeg=seg;}}
        //if(num<0){noNeg=true; seg=0;}//segment will not be all numbers
    }

    //print("tot:"+tot+" totCt:"+totCt)
   // print("max seg:"+maxSeg+" segCt:"+segCt)

    if(tot>maxSeg||(segCt==totCt&&tot==maxSeg&&arr[0]!=0&&arr[arr.length-1]!=0)){print("YES");}
    else{print("NO");}

}//num runs

var numRun= readline();

for(var n=0;n<numRun;n++){
    var k=readline();
    var arr=readline().split(" ").map(function(x){return parseInt(x);});

    var tot=0;
    var seg=0;
    var maxSeg=0;
    var totCt=0;
    var segCt=0;

    //print(arr);

    for(var i=0;i<arr.length;i++){
        //var num=parseInt(arr[i],10);
        var num=arr[i];
        tot+=num; totCt++;
        if(seg+num<=0){seg=0;segCt=0;}//go below zero by adding this number, start a new segment
        else{seg+=num;segCt++;if(seg>maxSeg){maxSeg=seg;}}
        //if(num>0){seg+=num; if(maxSeg<seg){maxSeg=seg;}}
        //if(num<0){noNeg=true; seg=0;}//segment will not be all numbers
    }

    //print("tot:"+tot+" totCt:"+totCt)
    //print("max seg:"+maxSeg+" segCt:"+segCt)

    if(tot>maxSeg||(segCt==totCt&&tot==maxSeg)){print("YES");}
    else{print("NO");}

}//num runs

var numRun= readline();

for(var n=0;n<numRun;n++){
    var k=readline();
    var arr=readline().split(" ").map(function(x){return parseInt(x);});

    var tot=0;
    var seg=0;
    var maxSeg=0;
    var totCt=0;
    var segCt=0;

    //print(arr);

    for(var i=0;i<arr.length;i++){
        //var num=parseInt(arr[i],10);
        var num=arr[i];
        tot+=num; totCt++;
        if(seg+num<=0){seg=0;segCt=0;}//go below zero by adding this number, start a new segment
        else{seg+=num;segCt++;if(seg>maxSeg){maxSeg=seg;}}
        //if(num>0){seg+=num; if(maxSeg<seg){maxSeg=seg;}}
        //if(num<0){noNeg=true; seg=0;}//segment will not be all numbers
    }

    print("tot:"+tot+" totCt:"+totCt)
    print("max seg:"+maxSeg+" segCt:"+segCt)

    if(tot>maxSeg||(segCt==totCt&&tot==maxSeg&&arr[0]!=0&&arr[arr.length-1]!=0)){print("YES");}
    else{print("NO");}

}//num runs

var numRun= readline();

for(var n=0;n<numRun;n++){
    var k=readline();
    var arr=readline().split(" ");

    var tot=0;
    var seg=0;
    var maxSeg=0;
    var noNeg=false;

    //print(arr);

    for(var i=0;i<arr.length;i++){
        var num=parseInt(arr[i],10);
        tot+=num;
        if(num>0){seg+=num; if(maxSeg<seg){maxSeg=seg;}}
        if(num<0){noNeg=true; seg=0;}//segment will not be all numbers
    }

    //print("tot: "+tot)
    //print("max seg: "+maxSeg)

    if(tot>maxSeg||!noNeg){print("YES");}
    else{print("NO");}

}//num runs

// '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 maxSubArraySum(array_of_numbers, array_size) {
  var max_so_far = Number.MIN_SAFE_INTEGER;
  var max_ending_here = 0;
  var start_index = 0;
  var end_index = 0;
  var start_tmp = 0;

  for (var i = 0; i < array_size; i++) {
    max_ending_here += array_of_numbers[i];

    if (max_so_far < max_ending_here) {
      max_so_far = max_ending_here;
      start_index = start_tmp;
      end_index = i;
    }

    if (max_ending_here < 0) {
      max_ending_here = 0;
      start_tmp = i + 1;
    }
  }
  return { max_so_far, start_index, end_index };
}

function main() {
  const test_cases = parseInt(readline(), 10);
  for(var i = 0; i < test_cases; i++) {
    const cupcakes_count = parseInt(readline(), 10);
    const cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));

    const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);

    const result = maxSubArraySum(cupcakes_taste, cupcakes_count);
    if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {
      print('YES');
    } else {
      if (total_taste > result.max_so_far) {
        print('YES');
      } else {
        print('NO');
      }
    }
  }
}
main();

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

main();

function main() {
  const test_cases = readline();
  for(var i = 0; i < test_cases; i++) {
    const cupcakes_count = readline();
    const cupcakes_taste = readline(); //.trim().split(' ').map(string => parseInt(string, 10));

    // const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);

    // const result = maxSubArraySum(cupcakes_taste, cupcakes_count);
    print(cupcakes_count, cupcakes_taste);
    // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {
    //   print('YES');
    // } else {
    //   if (total_taste > result.max_so_far) {
    //     print('YES');
    //   } else {
    //     print('NO');
    //   }
    // }
  }
}

function maxSubArraySum(array_of_numbers, array_size) {
  var max_so_far = Number.MIN_SAFE_INTEGER;
  var max_ending_here = 0;
  var start_index = 0;
  var end_index = 0;
  var start_tmp = 0;

  for (var i = 0; i < array_size; i++) {
    max_ending_here += array_of_numbers[i];

    if (max_so_far < max_ending_here) {
      max_so_far = max_ending_here;
      start_index = start_tmp;
      end_index = i;
    }

    if (max_ending_here < 0) {
      max_ending_here = 0;
      start_tmp = i + 1;
    }
  }
  return { max_so_far, start_index, end_index };
}

// '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 maxSubArraySum(array_of_numbers, array_size) {
  var max_so_far = Number.MIN_SAFE_INTEGER;
  var max_ending_here = 0;
  var start_index = 0;
  var end_index = 0;
  var start_tmp = 0;

  for (var i = 0; i < array_size; i++) {
    max_ending_here += array_of_numbers[i];

    if (max_so_far < max_ending_here) {
      max_so_far = max_ending_here;
      start_index = start_tmp;
      end_index = i;
    }

    if (max_ending_here < 0) {
      max_ending_here = 0;
      start_tmp = i + 1;
    }
  }
  return { max_so_far, start_index, end_index };
}

function main() {
  const test_cases = parseInt(readline(), 10);
  for(var i = 0; i < test_cases; i++) {
    const cupcakes_count = parseInt(readline(), 10);
    const cupcakes_taste = readline(); //.trim().split(' ').map(string => parseInt(string, 10));

    // const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);

    // const result = maxSubArraySum(cupcakes_taste, cupcakes_count);
    print(cupcakes_taste);
    // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {
    //   print('YES');
    // } else {
    //   if (total_taste > result.max_so_far) {
    //     print('YES');
    //   } else {
    //     print('NO');
    //   }
    // }
  }
}
main();

// '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 maxSubArraySum(array_of_numbers, array_size) {
  var max_so_far = Number.MIN_SAFE_INTEGER;
  var max_ending_here = 0;
  var start_index = 0;
  var end_index = 0;
  var start_tmp = 0;

  for (var i = 0; i < array_size; i++) {
    max_ending_here += array_of_numbers[i];

    if (max_so_far < max_ending_here) {
      max_so_far = max_ending_here;
      start_index = start_tmp;
      end_index = i;
    }

    if (max_ending_here < 0) {
      max_ending_here = 0;
      start_tmp = i + 1;
    }
  }
  return { max_so_far, start_index, end_index };
}

function main() {
  const test_cases = parseInt(readline(), 10);
  for(var i = 0; i < test_cases; i++) {
    var cupcakes_count = parseInt(readline(), 10);
    var cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));

    var total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);

    var result = maxSubArraySum(cupcakes_taste, cupcakes_count);

    if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {
      print('YES');
    } else {
      if (total_taste > result.max_so_far) {
        print('YES');
      } else {
        print('NO');
      }
    }
  }
}
main();

// '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 maxSubArraySum(array_of_numbers, array_size) {
  var max_so_far = Number.MIN_SAFE_INTEGER;
  var max_ending_here = 0;
  var start_index = 0;
  var end_index = 0;
  var start_tmp = 0;

  for (var i = 0; i < array_size; i++) {
    max_ending_here += array_of_numbers[i];

    if (max_so_far < max_ending_here) {
      max_so_far = max_ending_here;
      start_index = start_tmp;
      end_index = i;
    }

    if (max_ending_here < 0) {
      max_ending_here = 0;
      start_tmp = i + 1;
    }
  }
  return { max_so_far, start_index, end_index };
}

function main() {
  const test_cases = parseInt(readline(), 10);
  for(var i = 0; i < test_cases; i++) {
    const cupcakes_count = readline();
    const cupcakes_taste = readline(); //.trim().split(' ').map(string => parseInt(string, 10));

    // const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);

    // const result = maxSubArraySum(cupcakes_taste, cupcakes_count);
    print(cupcakes_count, cupcakes_taste);
    // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {
    //   print('YES');
    // } else {
    //   if (total_taste > result.max_so_far) {
    //     print('YES');
    //   } else {
    //     print('NO');
    //   }
    // }
  }
}
main();

// '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 maxSubArraySum(array_of_numbers, array_size) {
  var max_so_far = Number.MIN_SAFE_INTEGER;
  var max_ending_here = 0;
  var start_index = 0;
  var end_index = 0;
  var start_tmp = 0;

  for (var i = 0; i < array_size; i++) {
    max_ending_here += array_of_numbers[i];

    if (max_so_far < max_ending_here) {
      max_so_far = max_ending_here;
      start_index = start_tmp;
      end_index = i;
    }

    if (max_ending_here < 0) {
      max_ending_here = 0;
      start_tmp = i + 1;
    }
  }
  return { max_so_far, start_index, end_index };
}

function main() {
  const test_cases = parseInt(readline(), 10);
  for(var i = 0; i < test_cases; i++) {
    const cupcakes_count = parseInt(readline(), 10);
    const cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));

    const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);

    const result = maxSubArraySum(cupcakes_taste, cupcakes_count);
    print(cupcakes_taste, total_taste, result)
    // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {
    //   print('YES');
    // } else {
    //   if (total_taste > result.max_so_far) {
    //     print('YES');
    //   } else {
    //     print('NO');
    //   }
    // }
  }
}
main();

// '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 maxSubArraySum(array_of_numbers, array_size) {
  var max_so_far = Number.MIN_SAFE_INTEGER;
  var max_ending_here = 0;
  var start_index = 0;
  var end_index = 0;
  var start_tmp = 0;

  for (var i = 0; i < array_size; i++) {
    max_ending_here += array_of_numbers[i];

    if (max_so_far < max_ending_here) {
      max_so_far = max_ending_here;
      start_index = start_tmp;
      end_index = i;
    }

    if (max_ending_here < 0) {
      max_ending_here = 0;
      start_tmp = i + 1;
    }
  }
  return { max_so_far, start_index, end_index };
}

function main() {
  const test_cases = parseInt(readline(), 10);
  for(var i = 0; i < test_cases; i++) {
    const cupcakes_count = parseInt(readline(), 10);
    const cupcakes_taste = readline(); //.trim().split(' ').map(string => parseInt(string, 10));

    // const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);

    // const result = maxSubArraySum(cupcakes_taste, cupcakes_count);
    print(cupcakes_count, cupcakes_taste);
    // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {
    //   print('YES');
    // } else {
    //   if (total_taste > result.max_so_far) {
    //     print('YES');
    //   } else {
    //     print('NO');
    //   }
    // }
  }
}
main();

// 'use strict';

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

// let inputString = '';
// let currentLine = 0;

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

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

//   main();
// });

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

// function print(item) {
//   console.log(item);
// }

function maxSubArraySum(array_of_numbers, array_size) {
  var max_so_far = Number.MIN_SAFE_INTEGER;
  var max_ending_here = 0;
  var start_index = 0;
  var end_index = 0;
  var start_tmp = 0;

  for (var i = 0; i < array_size; i++) {
    max_ending_here += array_of_numbers[i];

    if (max_so_far < max_ending_here) {
      max_so_far = max_ending_here;
      start_index = start_tmp;
      end_index = i;
    }

    if (max_ending_here < 0) {
      max_ending_here = 0;
      start_tmp = i + 1;
    }
  }
  return { max_so_far, start_index, end_index };
}

function main() {
  const test_cases = parseInt(readline(), 10);
  for(var i = 0; i < test_cases; i++) {
    const cupcakes_count = parseInt(readline(), 10);
    const cupcakes_taste = readline().trim().split(' ').map(string => parseInt(string, 10));

    const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);

    const result = maxSubArraySum(cupcakes_taste, cupcakes_count);
    if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {
      print('YES');
    } else {
      if (total_taste > result.max_so_far) {
        print('YES');
      } else {
        print('NO');
      }
    }
  }
}

main();

// '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 maxSubArraySum(array_of_numbers, array_size) {
  var max_so_far = Number.MIN_SAFE_INTEGER;
  var max_ending_here = 0;
  var start_index = 0;
  var end_index = 0;
  var start_tmp = 0;

  for (var i = 0; i < array_size; i++) {
    max_ending_here += array_of_numbers[i];

    if (max_so_far < max_ending_here) {
      max_so_far = max_ending_here;
      start_index = start_tmp;
      end_index = i;
    }

    if (max_ending_here < 0) {
      max_ending_here = 0;
      start_tmp = i + 1;
    }
  }
  return { max_so_far, start_index, end_index };
}

function main() {
  const test_cases = readline();
  for(var i = 0; i < test_cases; i++) {
    const cupcakes_count = readline();
    const cupcakes_taste = readline(); //.trim().split(' ').map(string => parseInt(string, 10));

    // const total_taste = cupcakes_taste.reduce((a, b) => a + b, 0);

    // const result = maxSubArraySum(cupcakes_taste, cupcakes_count);
    print(cupcakes_count, cupcakes_taste);
    // if (result.start_index == 0 && result.end_index == cupcakes_count - 1) {
    //   print('YES');
    // } else {
    //   if (total_taste > result.max_so_far) {
    //     print('YES');
    //   } else {
    //     print('NO');
    //   }
    // }
  }
}
main();