In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n.

The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once.

In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.

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

var res = 0;
var swaps = [];
var temp = 0;

function selectionSort(sortMe)
{
    var i, j, tmp, tmp2;
    for (i = 0; i < sortMe.length - 1; i++)
    {
        tmp = i;
        for (j = i + 1; j < sortMe.length; j++){
            if (sortMe[j] < sortMe[tmp]){
                tmp = j;
            }
        }
        if(tmp!=i){
            tmp2 = sortMe[tmp];
            sortMe[tmp] = sortMe[i];
            sortMe[i] = tmp2;
            res++;
            swaps.push({x: i, y: tmp});
        }
	}
}

selectionSort(a);
print(res);
for(var i=0; i < swaps.length; i++){
	print(swaps[i].x + " " + swaps[i].y);
}

var n = parseInt(readline());
var nums = readline().split(' ').map(function(x){return parseInt(x)});
var min, k, tmp;
var step = [];

for(var i=0;i<nums.length;++i) {
  var min = nums[i];
  k = i;
  for(var j=i;j<nums.length;++j) {
    if (nums[j] < min) {
      min = nums[j];
      k = j;
    }
  }
  if (k != i) {
     step.push([i, k]);
  }
  tmp = nums[i];
  nums[i] = nums[k];
  nums[k] = tmp;
}

print(step.length);
if (step.length > 0)
  for(var i=0;i<step.length;++i)
    print(step[i][0] + ' ' + step[i][1]);

var n = parseInt(readline());
var list = readline().split(' ');
var ctr = 0;
var seq = [];
var tmp;
for(var i = 0; i < list.length - 1; i++) {
	var minId = i;
	list[i] = parseInt(list[i]);
	for(var j = i + 1; j < list.length; j++) {
		list[j] = parseInt(list[j]);
		if(list[j] < list[minId]) {
			minId = j;
		}
	}
	if(minId !== i) {
		ctr++;
		seq.push([i, minId]);
		tmp = list[i];
		list[i] = list[minId];
		list[minId] = tmp;
	}
}
print(ctr);
for(i = 0; i < ctr; i++) {
	print(seq[i][0] + ' ' + seq[i][1]);
}

var n = parseInt(readline());
var a = readline().split(' ');
var cnt = 0;
var b = [];
for (var i=0;i<n;i++) a[i] = parseInt(a[i]);
for (var i=0;i<n;i++){
	var k = i;
	for (var j=i+1;j<n;j++){
		if (a[j]<a[k]){
			k = j;
		}
	}
	if (k!=i){
		cnt++;
		b.push([i,k]);
		var tmp = a[i];
		a[i] = a[k];
		a[k] = tmp;
	}
}
print(cnt);
for(var i=0;i<cnt;i++){
	print(b[i][0]+' '+b[i][1]);
}

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

var res = 0;
var swaps = [];
var temp = 0;

function selectionSort(sortMe)
{
    var i, j, tmp, tmp2;
    for (i = 0; i < sortMe.length - 1; i++)
    {
        tmp = i;
        for (j = i + 1; j < sortMe.length; j++){
            if (sortMe[j] < sortMe[tmp]){
                tmp = j;
            }
        }
        if(tmp!=i){
            tmp2 = sortMe[tmp];
            sortMe[tmp] = sortMe[i];
            sortMe[i] = tmp2;
            res++;
            swaps.push({x: i, y: tmp2});
        }
	}
}

selectionSort(a);
print(res);
for(var i=0; i < swaps.length; i++){
	print(swaps[i].x + " " + swaps[i].y);
}

var n = parseInt(readline());
var list = readline().split(' ');
var ctr;
var seq = [];
for(var i = 0; i < list.length - 1; i++) {
	var minId = i;
	list[i] = parseInt(list[i]);
	for(var j = 1; j < list.length; j++) {
		list[j] = parseInt(list[j]);
		if(list[j] < list[minId]) {
			minId = j;
		}
	}
	if(minId !== i) {
		ctr++;
		seq.push([i, minId]);
	}
}
print(ctr);
for(i = 0; i < ctr - 1; i++) {
	print(seq[i] + ' ' + seq[i + 1]);
}

var n = parseInt(readline());
var a = readline().split(' ');
var cnt = 0;
var b = [];
for (var i=0;i<n;i++) a[i] = parseInt(a[i]);
for (var i=0;i<n;i++){
	var k = i;
	for (var j=i+1;j<n;j++){
		if (a[j]<a[k]){
			k = j;
		}
	}
	if (k!=i){
		cnt++;
		b.push([i,k]);
		var tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;
	}
}
print(cnt);
for(var i=0;i<cnt;i++){
	print(b[i][0]+' '+b[i][1]);
}

var n = parseInt(readline());
var a = new Array();
a = readline().split(' ');
for (var i=0;i<n;i++){
	var k = i;
	for (var j=i+1;j<n;j++){
		if (a[j]<a[k]){
			k = j;
		}
	}
	if (k!=i){
		var tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;
		print(i+" "+k);
	}
}

var n = parseInt(readline());
var a = new Array();
a = readline().split(' ');
for (var i=0;i<n;i++){
	var k = i;
	for (var j=i+1;j<n;j++){
		if (a[j]<a[k]){
			k = j;
		}
	}
	if (k!=i) print(i+" "+k);
}


The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).

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

In the first line of the output print $$$k$$$ — the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.

NoteThe first example is described in the problem statement.

const n = parseInt(readline());
const a = readline().split(' ').map(x => parseInt(x));

var answer = '';
var first_ind = 0, last_ind = a.length - 1;
var maxi = 0;
var first, last;

while (first_ind <= last_ind) {
    first = a[first_ind];
    last = a[last_ind];
    if (first < last) {
        if (first > maxi) {
            answer += 'L';
            maxi = first;
            ++first_ind;
        } else if (last > maxi) {
            answer += 'R';
            maxi = last;
            --last_ind;
        } else {
            break;
        }
    } else if (first > last) {
        if (last > maxi) {
            answer += 'R';
            maxi = last;
            --last_ind;
        } else if (first > maxi) {
            answer += 'L';
            maxi = first;
            ++first_ind;
        } else {
            break;
        }
    } else {
        var from_left = 0;
        var left = first_ind;
        var maxi_left = maxi;
        while (left <= last_ind && a[left] > maxi_left) {
            ++from_left;
            maxi_left = a[left];
            ++left;
        }
        var from_right = 0;
        var right = last_ind;
        var maxi_right = maxi;
        while (right >= first_ind && a[right] > maxi_right) {
            ++from_right;
            maxi_right = a[right];
            --right;
        }

        if (from_left > from_right) {
            answer += 'L'.repeat(from_left);
        } else {
            answer += 'R'.repeat(from_right);
        }
        break;
    }
}

print(answer.length);
print(answer);


The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,  The chosen c prisoners has to form a contiguous segment of prisoners.  Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer. Find the number of ways you can choose the c prisoners.

The first line of input will contain three space separated integers n (1 ≤ n ≤ 2·105), t (0 ≤ t ≤ 109) and c (1 ≤ c ≤ n). The next line will contain n space separated integers, the ith integer is the severity ith prisoner's crime. The value of crime severities will be non-negative and will not exceed 109.

Print a single integer — the number of ways you can choose the c prisoners.

(function() {
    var s = readline().split(' ');
    var n = parseInt(s[0]);
    var t = parseInt(s[1]);
    var c = parseInt(s[2]);
    s = readline().split(' ');
    var i, a = [-1];
    for(i = 0 ; i < n ; ++i){
        if ( parseInt(s[i]) > t ){
            a.push(i);
        }
    }
    a.push(n);
    var diff, result = 0;
    for(i = 1 ; i < a.length ; ++i){
        diff = a[i] - a[i-1] - 1;
        result += Math.max(diff-c+1,0);
    }
    print(result);
})();

if (!this.readline) print = console.log, readline = require('./readline');

print(function(n, t, c) {
  var a = readline().split(' ').map(Number);

  var count = 0;
  var ans = 0;
  for (var i = 0; i < n; i++) {
    if (a[i] <= t) {
      count++;
      if (count >= c) {
        ans++;
      }
    } else {
      count = 0;
    }
  }
  return ans;

}.apply(0, readline().split(' ').map(Number)));

var ntc = readline().trim().split(' ').map((x)=>parseInt(x))
var n=ntc[0],t=ntc[1],c=ntc[2];
var x = readline().trim().split(' ').map((x)=>parseInt(x))
var ans =0;
var p=[];
for(var i=0;i<n;i++){
    if(x[i]>t)
        p.push(i)
}
if(p.length==0)
    ans = n-c+1;
else{
    for(var i=0;i<p.length;i++){
        ans+=Math.max(p[i]-(i==0?(-1):p[i-1])-c,0);
    }
    ans+=Math.max(n-p.pop()-c,0);
}

print(ans);

;(function () {

	var n = readline().split(' '), t, c, p = readline().split(' ').map(Number), k = 0, l = 0;
	t = +n[1];
	c = +n[2];
	n = +n[0];

	for (var i = 0; i < n; i++) {
		if (p[i] <= t) l++;
		else l = 0;

		if (l >= c) k++;
	}

	print(k);

}).call(this);

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

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

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

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], maxCrime = data[1], minSpan = data[2],
		count = 0,
		crimes = tokenizeIntegers(readline()),
		span = 0;
	for (var i = 0; i < n; ++i) {
		if (crimes[i] <= maxCrime) {
			++span;
			if (span >= minSpan) {
				++count;
			}
		} else {
			span = 0;
		}
	}
	print(count);
}

main();

var tmp = readline().split(' ');
var t = parseInt(tmp[1]);
var c = parseInt(tmp[2]);
var items = readline().split(' ');
var answ = 0, size = 0;

for( var i = 0; i < items.length; ++i) {
  if (parseInt(items[i]) <= t ) {
    size++;
  } else {
    if(size >= c){
      answ += 1 + size - c;
    }
    size = 0;
  }
}

if(size >= c) answ += 1 + size - c;

print(answ);

var tok = null;
var index = 0;
function next() {
    while (tok == null || index == tok.length) {
        tok = readline().split(' ');
        index = 0;
    }
    var res = tok[index++];
    return res;
}

function nextInt() {
    return parseInt(next());
}

function main() {
    var n;
    var t;
    var c;
    n = nextInt();
    t = nextInt();
    c = nextInt();
    var pre = 0;
    var result = 0;
    for (var i = 0; i < n; i++) {
        var x = nextInt();
        if (x > t) {
            if (i - pre >= c) {
                result += (i - pre + 1 - c);
            }
            pre = i + 1;
        }
    }
    if(n-pre>=c){
    result += (n - pre + 1 - c);
    }
    print(result);
}

main();

"use strict";

var _slicedToArray = (function() {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;
    try {
      for (
        var _i = arr[Symbol.iterator](), _s;
        !(_n = (_s = _i.next()).done);
        _n = true
      ) {
        _arr.push(_s.value);
        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
  return function(arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError(
        "Invalid attempt to destructure non-iterable instance"
      );
    }
  };
})();

var compose = function compose() {
  for (
    var _len = arguments.length, functions = Array(_len), _key = 0;
    _key < _len;
    _key++
  ) {
    functions[_key] = arguments[_key];
  }

  return function() {
    for (
      var _len2 = arguments.length, args = Array(_len2), _key2 = 0;
      _key2 < _len2;
      _key2++
    ) {
      args[_key2] = arguments[_key2];
    }

    return functions.reduce(function(currArgs, func) {
      return func(currArgs);
    }, args);
  };
};

var lineToNumberArray = function lineToNumberArray(str) {
  return str.split(" ").map(function(num) {
    return parseInt(num, 10);
  });
};

var readNumbersLine = compose(
  readline,
  lineToNumberArray
);

var _readNumbersLine = readNumbersLine(),
  _readNumbersLine2 = _slicedToArray(_readNumbersLine, 3),
  n = _readNumbersLine2[0],
  t = _readNumbersLine2[1],
  c = _readNumbersLine2[2];

var arr = readNumbersLine();
var lastTOver = -1;
var res = 0;

var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (
    var _iterator = arr.entries()[Symbol.iterator](), _step;
    !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
    _iteratorNormalCompletion = true
  ) {
    var _ref = _step.value;

    var _ref2 = _slicedToArray(_ref, 2);

    var key = _ref2[0];
    var value = _ref2[1];

    if (value > t) lastTOver = key;
    if (key - lastTOver >= c) res++;
  }
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    if (!_iteratorNormalCompletion && _iterator.return) {
      _iterator.return();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}

print(res);

var tmp = readline().split(' ');
var t = parseInt(tmp[1]);
var c = parseInt(tmp[2]);
var items = readline().split(' ');
var answ = 0, size = 0;

for( var i = 0; i < items.length; ++i) {
  if (parseInt(items[i]) <= t ) {
    size++;
  } else if(size >= c){
    answ += 1 + size - c;
    size = 0;
  }
}

if(size >= c) answ += 1 + size - c;

print(answ);

var tmp = readline().split(' ');
var t = parseInt(tmp[1]);
var c = parseInt(tmp[2]);
var items = readline().split(' ');
var answ = 0, size = 0;

for( var i = 0; i < items.length; ++i) {
  if (parseInt(items[i]) <= t ) {
    size++;
  } else {
    answ += 1 + size - c;
    size = 0;
  }
}

answ += 1 + size - c;

print(answ);

(function() {
    var s = readline().split(' ');
    var n = parseInt(s[0]);
    var t = parseInt(s[1]);
    var c = parseInt(s[2]);
    s = readline().split(' ');
    var i, a = [-1];
    for(i = 0 ; i < n ; ++i){
        if ( parseInt(s[i]) > t ){
            a.push(i);
        }
    }
    a.push(n);
    var diff, result = 0;
    for(i = 1 ; i < s.length ; ++i){
        diff = a[i] - a[i-1] + 1;
        result += Math.max(diff-parseInt(c)+1,0);
    }
    print(result);
})();


Michael and Joe are playing a game. The game is played on a grid with $$$n$$$ rows and $$$m$$$ columns, filled with distinct integers. We denote the square on the $$$i$$$-th ($$$1\le i\le n$$$) row and $$$j$$$-th ($$$1\le j\le m$$$) column by $$$(i, j)$$$ and the number there by $$$a_{ij}$$$.Michael starts by saying two numbers $$$h$$$ ($$$1\le h \le n$$$) and $$$w$$$ ($$$1\le w \le m$$$). Then Joe picks any $$$h\times w$$$ subrectangle of the board (without Michael seeing).Formally, an $$$h\times w$$$ subrectangle starts at some square $$$(a,b)$$$ where $$$1 \le a \le n-h+1$$$ and $$$1 \le b \le m-w+1$$$. It contains all squares $$$(i,j)$$$ for $$$a \le i \le a+h-1$$$ and $$$b \le j \le b+w-1$$$.    Possible move by Joe if Michael says $$$3\times 2$$$ (with maximum of $$$15$$$). Finally, Michael has to guess the maximum number in the subrectangle. He wins if he gets it right.Because Michael doesn't like big numbers, he wants the area of the chosen subrectangle (that is, $$$h \cdot w$$$), to be as small as possible, while still ensuring that he wins, not depending on Joe's choice. Help Michael out by finding this minimum possible area. It can be shown that Michael can always choose $$$h, w$$$ for which he can ensure that he wins.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 40$$$)  — the size of the grid. Each of the following $$$n$$$ lines contains $$$m$$$ integers. The $$$j$$$-th integer on the $$$i$$$-th line is $$$a_{ij}$$$ ($$$-10^9 \le a_{ij} \le 10^9$$$)  — the element in the cell $$$(i, j)$$$. It is guaranteed that all the numbers are distinct (that is, if $$$a_{i_1j_1} = a_{i_2j_2}$$$, then $$$i_1 = i_2, j_1 = j_2$$$).

For each test case print a single positive integer  — the minimum possible area the subrectangle can have while still ensuring that Michael can guarantee the victory.

NoteIn the first test case, the grid is $$$1\times 1$$$, so the only possible choice for $$$h, w$$$ is $$$h = 1, w = 1$$$, giving an area of $$$h\cdot w = 1$$$.The grid from the second test case is drawn in the statement. It can be shown that with $$$h = 3, w = 3$$$ Michael can guarantee the victory and that any choice with $$$h\cdot w \le 8$$$ doesn't.

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

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

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

function main() {
    var t = parseInt(readline());

    for (let i = 0; i < t; i++) {
        var x = readline().split(' ');
        var n = parseInt(x[0]);
        var m = parseInt(x[1]);

        var a = [];
        var I = 0, J = 0, maxf = Number.NEGATIVE_INFINITY;
        for (let j = 0; j < n; j++) {
            a[j] = readline().split(' ');
            var max = Number.NEGATIVE_INFINITY;
            var J_ = 0;
            for (let k = 0; k < m; k++) {
                a[j][k] = parseInt(a[j][k]);
                if (max < a[j][k]) {
                    max = a[j][k];
                    J_ = k;
                }
            }

            if (max > maxf) {
                maxf = max;
                I = j;
                J = J_;
            }
        }

        var h = Math.max(I+1, n-I);
        var w = Math.max(J+1, m-J);

        console.log(h*w);
    }
}

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

/***
Codeforces Round #801 (Div. 2) and EPIC Institute of Technology Round
2022-06-18

A. Subrectangle Guess
***/

function main() {
  var t = readline();
  t = parseInt(t);
  for (let i = 0; i < t; i++) {
    let dim_in = readline();
    dim_in = dim_in.split(" ");
    dim_in = dim_in.map((k) => parseInt(k));
    const n = parseInt(dim_in[0]);
    const m = parseInt(dim_in[1]);

    let cur_max = -1e10;
    let max_row, max_col;

    // Strategy: find the max value and return the largest area of
    // the rectangle between that location and a corner
    for (let row = 0; row < n; row++) {
      let cur_row = readline();
      cur_row = cur_row.split(" ");
      cur_row = cur_row.map((k) => parseInt(k));
      for (let col = 0; col < m; col++) {
        if (cur_row[col] > cur_max) {
          cur_max = cur_row[col];
          max_row = row;
          max_col = col;
        }
      }
    }

    console.log(
      Math.max(
        (max_row + 1) * (max_col + 1),
        (max_row + 1) * (m - max_col),
        (n - max_row) * (max_col + 1),
        (n - max_row) * (m - max_col)
      )
    );
  }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function output(x) {
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

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

    for (let i = 0; i < N; i++) {
        let [n, m] = readline().split(' ').map(Number);

        let max = -Infinity;
        let maxN = -1;
        let maxM = -1;
        for (let j = 0; j < n; j++) {
            let row = readline().split(' ').map(Number);
            for (let k = 0; k < m; k++) {
                if (row[k] > max) {
                    max = row[k];
                    maxN = j + 1;
                    maxM = k + 1;
                }
            }
        }

        let offsetN = Math.max(Math.abs(n - maxN + 1), maxN);
        let offsetM = Math.max(Math.abs(m - maxM + 1), maxM);

        output(offsetN * offsetM);
    }
}

'use strict';

function solve(n, m, a) {
  const max = Math.max(...a.flat());
  let r = 0,
      c = 0;
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if (max === a[i][j]) {
        r = Math.max(i + 1, n - i);
        c = Math.max(j + 1, m - j);
        return r * c;
      }
    }
  }
  return -1;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = [];
      let tmp = n;
      while (tmp--) {
        a.push((await read()).split(' ').map(Number));
      }
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

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

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

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

function main() {
    var t = parseInt(readline());

    for (let i = 0; i < t; i++) {
        var x = readline().split(' ');
        var n = parseInt(x[0]);
        var m = parseInt(x[1]);

        var a = [];
        var I = 0, J = 0, maxf = 0;
        for (let j = 0; j < n; j++) {
            a[j] = readline().split(' ');
            var max = 0;
            var J_ = 0;
            for (let k = 0; k < m; k++) {
                a[j][k] = parseInt(a[j][k]);
                if (max < a[j][k]) {
                    max = a[j][k];
                    J_ = k;
                }
            }

            if (max > maxf) {
                maxf = max;
                I = j;
                J = J_;
            }
        }

        var h = Math.max(I+1, n-I);
        var w = Math.max(J+1, m-J);

        console.log(h*w);
    }
}


$$$n$$$ towns are arranged in a circle sequentially. The towns are numbered from $$$1$$$ to $$$n$$$ in clockwise order. In the $$$i$$$-th town, there lives a singer with a repertoire of $$$a_i$$$ minutes for each $$$i \in [1, n]$$$.Each singer visited all $$$n$$$ towns in clockwise order, starting with the town he lives in, and gave exactly one concert in each town. In addition, in each town, the $$$i$$$-th singer got inspired and came up with a song that lasts $$$a_i$$$ minutes. The song was added to his repertoire so that he could perform it in the rest of the cities.Hence, for the $$$i$$$-th singer, the concert in the $$$i$$$-th town will last $$$a_i$$$ minutes, in the $$$(i + 1)$$$-th town the concert will last $$$2 \cdot a_i$$$ minutes, ..., in the $$$((i + k) \bmod n + 1)$$$-th town the duration of the concert will be $$$(k + 2) \cdot a_i$$$, ..., in the town $$$((i + n - 2) \bmod n + 1)$$$ — $$$n \cdot a_i$$$ minutes.You are given an array of $$$b$$$ integer numbers, where $$$b_i$$$ is the total duration of concerts in the $$$i$$$-th town. Reconstruct any correct sequence of positive integers $$$a$$$ or say that it is impossible.

The first line contains one integer $$$t$$$ $$$(1 \le t \le 10^3$$$) — the number of test cases. Then the test cases follow. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$1 \le n \le 4 \cdot 10^4$$$) — the number of cities. The second line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^{9}$$$) — the total duration of concerts in $$$i$$$-th city. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the answer as follows: If there is no suitable sequence $$$a$$$, print NO. Otherwise, on the first line print YES, on the next line print the sequence $$$a_1, a_2, \dots, a_n$$$ of $$$n$$$ integers, where $$$a_i$$$ ($$$1 \le a_i \le 10^{9}$$$) is the initial duration of repertoire of the $$$i$$$-th singer. If there are multiple answers, print any of them.

NoteLet's consider the $$$1$$$-st test case of the example:  the $$$1$$$-st singer in the $$$1$$$-st city will give a concert for $$$3$$$ minutes, in the $$$2$$$-nd — for $$$6$$$ minutes, in the $$$3$$$-rd — for $$$9$$$ minutes;  the $$$2$$$-nd singer in the $$$1$$$-st city will give a concert for $$$3$$$ minutes, in the $$$2$$$-nd — for $$$1$$$ minute, in the $$$3$$$-rd - for $$$2$$$ minutes;  the $$$3$$$-rd singer in the $$$1$$$-st city will give a concert for $$$6$$$ minutes, in the $$$2$$$-nd — for $$$9$$$ minutes, in the $$$3$$$-rd — for $$$3$$$ minutes.

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

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

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

		let sm = 0;
		for (const x of b) {
			sm += x;
		}

		const d = n*(n+1)/2
		if (sm%d) {
			console.log('NO');
			continue;
		}

		sm /= d;

		let ans = [];
		for (let i = 0; i < n; i++) {
			ans[i] = (b[(i+n-1)%n]-(b[i]-sm))/n;
			if (ans[i] <= 0 || ans[i]%1) {
				ans = false;
				break;
			}
		}

		console.log(ans ? 'YES\n' + ans.join(' ') : 'NO');
	}
}

'use strict';

function solve(n, a) {
  const res = [];
  let sum = a.reduce((a, b) => a + b, 0);
  if (sum % (n * (n + 1) / 2) !== 0) return 'NO';
  sum /= n * (n + 1) / 2;
  for (let i = 0; i < n; i++) {
    res[i] = sum - (a[i] - a[(i - 1 + n) % n]);
    if (res[i] % n !== 0) return 'NO';
    if (res[i] <= 0) return 'NO';
    res[i] /= n;
  }
  return `YES\n${res.join(' ')}`;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

"use strict";

function matprint(mat) {
  let shape = [mat.length, mat[0].length];
  function col(mat, i) {
    return mat.map((row) => row[i]);
  }
  let colMaxes = [];
  for (let i = 0; i < shape[1]; i++) {
    colMaxes.push(
      Math.max.apply(
        null,
        col(mat, i).map((n) => n.toString().length)
      )
    );
  }

  mat.forEach((row) => {
    console.log.apply(
      null,
      row.map((val, j) => {
        return new Array(colMaxes[j] - val.toString().length + 1).join(" ") + val.toString() + "  ";
      })
    );
  });
}

const nQueues = this.readline().split(" ");

// For this problem we will apply Gauss elimination algorithm

for (let i = 0; i < nQueues; i++) {
  const n = Number(this.readline());
  const minutes = this.readline()
    .split(" ")
    .map((e) => Number(e));
  const sum = minutes.reduce((prev, curr) => prev + curr, 0);
  const totalRep = (n * (n + 1)) / 2;

  if (sum % totalRep) {
    this.print("NO");
    continue;
  }

  const ans = new Array(n);

  let fail = false;
  for (let x = 0; x < n; x++) {
    ans[x] = (minutes[(n - 1 + x) % n] - minutes[x] + sum / totalRep) / n;

    if (ans[x] <= 0 || Math.abs(ans[x] - Math.round(ans[x])) > 0.0000001) {
      this.print("NO");
      fail = true;
      break;
    }
  }

  if (!fail) {
    this.print("YES");
    this.print(ans.join(" "));
  }
}

var t = parseInt(readline());

  function solve() {
    var n = parseInt(readline());
    var a = readline()
      .split(" ")
      .map((data) => +data);
    var ans = [];
    var total = 0;
    for (var i = 0; i < n; i++) {
      total += a[i];
    }
    var sum = (n * (n + 1)) / 2;
    if (total % sum) {
      print("NO");
      return;
    }
    total /= sum;
    for (var i = 0; i < n; i++) {
      var diff = a[i] - a[(n - 1 + i) % n];
      diff = total - diff;
      if (diff <= 0 || diff % n) {
        print("NO");
        return;
      }
      diff /= n;
      ans[i] = diff;
    }
    print("YES");
    var an = "";
    for (var i of ans) {
      an += i + " ";
    }
    print(an);
  }

  while (t--) {
    solve();
  }

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

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

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

		let sm = 0;
		for (const x of b) {
			sm += x;
		}

		const d = n*(n+1)/2
		if (sm%d) {
			console.log('NO');
			continue;
		}

		sm /= d;

		let ans = [];
		for (let i = 0; i < n; i++) {
			ans[i] = (b[(i+n-1)%n]-(b[i]-sm))/n;
			if (ans[i] <= 0) {
				ans = false;
				break;
			}
		}

		console.log(ans ? 'YES\n' + ans.join(' ') : 'NO');
	}
}

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

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

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

		let sm = 0;
		for (const x of b) {
			sm += x;
		}

		const d = n*(n+1)/2
		if (sm%d) {
			console.log('NO');
			return;
		}

		sm /= d;

		let ans = [];
		for (let i = 0; i < n; i++) {
			ans[i] = (b[(i+n-1)%n]-(b[i]-sm))/n;
			if (ans[i] <= 0 || ans[i] > n) {
				ans = false;
				break;
			}
		}

		console.log(ans ? 'YES\n' + ans.join(' ') : 'NO');
	}
}

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

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

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

		let sm = 0;
		for (const x of b) {
			sm += x;
		}

		sm = 2*sm/(n*(n+1));

		let ans = [];
		for (let i = 0; i < n; i++) {
			ans[i] = (b[(i+n-1)%n]-(b[i]-sm))/n;
			if (ans[i] <= 0 || ans[i] > n) {
				ans = false;
				break;
			}
		}

		console.log(ans ? 'YES\n' + ans.join(' ') : 'NO');
	}
}

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

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

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

		let sm = 0;
		for (const x of b) {
			sm += x;
		}

		sm = 2*sm/(n*(n+1));

		let ans = [];
		for (let i = 0; i < n; i++) {
			ans[i] = (b[(i+n-1)%n]-(b[i]-sm))/n;
			if (ans[i] == 0) {
				ans = false;
				break;
			}
		}

		console.log(ans ? 'YES\n' + ans.join(' ') : 'NO');
	}
}

"use strict";

function matprint(mat) {
  let shape = [mat.length, mat[0].length];
  function col(mat, i) {
    return mat.map((row) => row[i]);
  }
  let colMaxes = [];
  for (let i = 0; i < shape[1]; i++) {
    colMaxes.push(
      Math.max.apply(
        null,
        col(mat, i).map((n) => n.toString().length)
      )
    );
  }

  mat.forEach((row) => {
    console.log.apply(
      null,
      row.map((val, j) => {
        return new Array(colMaxes[j] - val.toString().length + 1).join(" ") + val.toString() + "  ";
      })
    );
  });
}

const nQueues = this.readline().split(" ");

// For this problem we will apply Gauss elimination algorithm

for (let i = 0; i < nQueues; i++) {
  const n = Number(this.readline());
  const minutes = this.readline()
    .split(" ")
    .map((e) => Number(e));

  const matrix = [];
  /* generate matrix with the coefficient of the repertoire for each singer
   * For 6 cities, it'll look like this:
      1   6   5   4   3   2   81
      2   1   6   5   4   3   75
      3   2   1   6   5   4   75
      4   3   2   1   6   5   93
      5   4   3   2   1   6   93
      6   5   4   3   2   1   87
   */
  for (let city = 0; city < n; city++) {
    matrix[city] = [];
    for (let singer = 0; singer < n; singer++) {
      matrix[city][singer] = 1 + ((city + (n - singer)) % n);
    }
    matrix[city].push(minutes[city]);
  }

  /* Now, we will get the matrix to echelon form, that is, something like this
    1   6                     5                    4                     3                      2                   81
    0   1   0.36363636363636365   0.2727272727272727   0.18181818181818182    0.09090909090909091    7.909090909090909
    0   0                     1                  0.2    0.1333333333333333    0.06666666666666671   5.0666666666666655
    0   0                     0                    1    0.1111111111111111   0.055555555555555476   1.7222222222222239
    0   0                     0                    0                     1    0.05000000000000005    4.249999999999998
    0   0                     0                    0                     0                      1   5.0000000000000036

    which will help us isolate each variable
  */
  for (let a = 0; a < n; a++) {
    const factor1 = matrix[a][a];
    for (let col = a; col <= n; col++) {
      matrix[a][col] = matrix[a][col] / factor1;
    }
    for (let lin = a + 1; lin < n; lin++) {
      const factor2 = matrix[lin][a];
      for (let col = a; col <= n; col++) {
        matrix[lin][col] = matrix[lin][col] / factor2 - matrix[a][col];
      }
    }
  }

  /* Now we start from the bottom and subtract for each equation the free variables, which will give us something like this
    (rounding is actually done later, but I've done here just for clarity)
      1   0   0   0   0   0   5
      0   1   0   0   0   0   5
      0   0   1   0   0   0   4
      0   0   0   1   0   0   1
      0   0   0   0   1   0   4
      0   0   0   0   0   1   5

      Which makes it trivial to find the values of each variable
  */
  for (let a = n - 1; a >= 0; a--) {
    for (let lin = a - 1; lin >= 0; lin--) {
      const factor = matrix[lin][a];
      for (let col = n; col >= a; col--) {
        matrix[lin][col] = matrix[lin][col] - factor * matrix[a][col];
      }
    }
  }

  const vars = [];
  for (let a = 0; a < n; a++) {
    if (matrix[a][n] <= 0) {
      // repertoires must have positive duration
      this.print("NO");
      break;
    }
    if (matrix[a][n] - Math.round(matrix[a][n]) > 0.000001) {
      // not an integer
      this.print("NO");
      break;
    }
    vars.push(Math.round(matrix[a][n]));
  }
  if (vars.length === n) {
    this.print("YES");
    this.print(vars.join(" "));
  }
}

"use strict";

function matprint(mat) {
  let shape = [mat.length, mat[0].length];
  function col(mat, i) {
    return mat.map((row) => row[i]);
  }
  let colMaxes = [];
  for (let i = 0; i < shape[1]; i++) {
    colMaxes.push(
      Math.max.apply(
        null,
        col(mat, i).map((n) => n.toString().length)
      )
    );
  }

  mat.forEach((row) => {
    console.log.apply(
      null,
      row.map((val, j) => {
        return new Array(colMaxes[j] - val.toString().length + 1).join(" ") + val.toString() + "  ";
      })
    );
  });
}

const nQueues = this.readline().split(" ");

// For this problem we will apply Gauss elimination algorithm

for (let i = 0; i < nQueues; i++) {
  const n = Number(this.readline());
  const minutes = this.readline()
    .split(" ")
    .map((e) => Number(e));

  const matrix = [];
  /* generate matrix with the coefficient of the repertoire for each singer
   * For 6 cities, it'll look like this:
      1   6   5   4   3   2   81
      2   1   6   5   4   3   75
      3   2   1   6   5   4   75
      4   3   2   1   6   5   93
      5   4   3   2   1   6   93
      6   5   4   3   2   1   87
   */
  for (let city = 0; city < n; city++) {
    matrix[city] = [];
    for (let singer = 0; singer < n; singer++) {
      matrix[city][singer] = 1 + ((city + (n - singer)) % n);
    }
    matrix[city].push(minutes[city]);
  }

  /* Now, we will get the matrix to echelon form, that is, something like this
    1   6                     5                    4                     3                      2                   81
    0   1   0.36363636363636365   0.2727272727272727   0.18181818181818182    0.09090909090909091    7.909090909090909
    0   0                     1                  0.2    0.1333333333333333    0.06666666666666671   5.0666666666666655
    0   0                     0                    1    0.1111111111111111   0.055555555555555476   1.7222222222222239
    0   0                     0                    0                     1    0.05000000000000005    4.249999999999998
    0   0                     0                    0                     0                      1   5.0000000000000036

    which will help us isolate each variable
  */
  for (let a = 0; a < n; a++) {
    const factor1 = matrix[a][a];
    for (let col = a; col <= n; col++) {
      matrix[a][col] = matrix[a][col] / factor1;
    }
    for (let lin = a + 1; lin < n; lin++) {
      const factor2 = matrix[lin][a];
      for (let col = a; col <= n; col++) {
        matrix[lin][col] = matrix[lin][col] / factor2 - matrix[a][col];
      }
    }
  }

  /* Now we start from the bottom and subtract for each equation the free variables, which will give us something like this
    (rounding is actually done later, but I've done here just for clarity)
      1   0   0   0   0   0   5
      0   1   0   0   0   0   5
      0   0   1   0   0   0   4
      0   0   0   1   0   0   1
      0   0   0   0   1   0   4
      0   0   0   0   0   1   5

      Which makes it trivial to find the values of each variable
  */
  for (let a = n - 1; a >= 0; a--) {
    for (let lin = a - 1; lin >= 0; lin--) {
      const factor = matrix[lin][a];
      for (let col = n; col >= a; col--) {
        matrix[lin][col] = matrix[lin][col] - factor * matrix[a][col];
      }
    }
  }

  const vars = [];
  for (let a = 0; a < n; a++) {
    if (matrix[a][n] <= 0) {
      // repertoires must have positive duration
      this.print("NO");
      break;
    }
    if (matrix[a][n] - Math.round(matrix[a][n]) > 0.1) {
      // not an integer
      this.print("NO");
      break;
    }
    vars.push(Math.round(matrix[a][n]));
  }
  if (vars.length === n) {
    this.print("YES");
    this.print(vars.join(" "));
  }
}

"use strict";

function matprint(mat) {
  let shape = [mat.length, mat[0].length];
  function col(mat, i) {
    return mat.map((row) => row[i]);
  }
  let colMaxes = [];
  for (let i = 0; i < shape[1]; i++) {
    colMaxes.push(
      Math.max.apply(
        null,
        col(mat, i).map((n) => n.toString().length)
      )
    );
  }

  mat.forEach((row) => {
    console.log.apply(
      null,
      row.map((val, j) => {
        return new Array(colMaxes[j] - val.toString().length + 1).join(" ") + val.toString() + "  ";
      })
    );
  });
}

const nQueues = this.readline().split(" ");

for (let i = 0; i < nQueues; i++) {
  const n = Number(this.readline());
  const minutes = this.readline()
    .split(" ")
    .map((e) => Number(e));

  const matrix = [];
  for (let city = 0; city < n; city++) {
    matrix[city] = [];
    for (let singer = 0; singer < n; singer++) {
      matrix[city][singer] = 1 + ((city + (n - singer)) % n);
    }
    matrix[city].push(minutes[city]);
  }

  for (let a = 0; a < n; a++) {
    const f1 = matrix[a][a];
    for (let col = a; col <= n; col++) {
      matrix[a][col] = matrix[a][col] / f1;
    }
    for (let lin = a + 1; lin < n; lin++) {
      const f2 = matrix[lin][a];
      for (let col = a; col <= n; col++) {
        matrix[lin][col] = matrix[lin][col] - f2 * matrix[a][col];
      }
    }
  }

  for (let a = n - 1; a >= 0; a--) {
    for (let lin = a - 1; lin >= 0; lin--) {
      const fator = matrix[lin][a];
      for (let col = n; col >= a; col--) {
        matrix[lin][col] = matrix[lin][col] - fator * matrix[a][col];
      }
    }
  }

  const vars = [];
  for (let a = 0; a < n; a++) {
    if (matrix[a][n] <= 0) {
      this.print("NO");
      break;
    }
    vars.push(Math.round(matrix[a][n]));
  }
  if (vars.length === n) {
    this.print("YES");
    this.print(vars.join(" "));
  }
}


Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:(1n + 2n + 3n + 4n) mod 5for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).

The single line contains a single integer n (0 ≤ n ≤ 10105). The number doesn't contain any leading zeroes.

Print the value of the expression without leading zeros.

NoteOperation x mod y means taking remainder after division x by y.Note to the first sample:

;(function () {

	print((+readline().slice(-2)) % 4 ? 0 : 4);

}).call(this);

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

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

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

function main() {
	var s = trim(readline()),
		n = parseInt(s.substring(s.length-2)),
		two = [1, 2, 4, 3][n%4],
		three = [1, 3, 4, 2][n%4],
		four = [1, 4][n%2];
	print((1 + two + three + four) % 5);
}

main();


You are given an array $$$a$$$ of $$$n$$$ integers. You are asked to find out if the inequality $$$$$$\max(a_i, a_{i + 1}, \ldots, a_{j - 1}, a_{j}) \geq a_i + a_{i + 1} + \dots + a_{j - 1} + a_{j}$$$$$$ holds for all pairs of indices $$$(i, j)$$$, where $$$1 \leq i \leq j \leq n$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the size of the array. The next line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, on a new line output "YES" if the condition is satisfied for the given array, and "NO" otherwise. You can print each letter in any case (upper or lower).

NoteIn test cases $$$1$$$ and $$$2$$$, the given condition is satisfied for all $$$(i, j)$$$ pairs. In test case $$$3$$$, the condition isn't satisfied for the pair $$$(1, 2)$$$ as $$$\max(2, 3) < 2 + 3$$$.

'use strict';

function solve(n, a) {
  const segTree = new SegTree(n + 1);
  segTree.update(0, 0);
  let sum = 0;
  for (let [i, num] of a.entries()) {
    sum += num;
    segTree.update(i + 1, sum);
  }
  const left = [],
        right = [];
  {
    const stack = [];
    for (let i = 0; i < n; i++) {
      while (stack.length && a[stack[stack.length - 1]] <= a[i]) stack.pop();
      if (stack.length) left[i] = stack[stack.length - 1] + 1;else left[i] = 0;
      stack.push(i);
    }
  }
  {
    const stack = [];
    for (let i = n - 1; i >= 0; i--) {
      while (stack.length && a[stack[stack.length - 1]] <= a[i]) stack.pop();
      if (stack.length) right[i] = stack[stack.length - 1] + 1;else right[i] = n + 1;
      stack.push(i);
    }
  }
  for (let i = 0; i < n; i++) {
    const l = left[i],
          r = right[i];
    const lmin = segTree.min(l, i),
          rmax = segTree.max(i + 1, r - 1);
    if (rmax - lmin > a[i]) return 'NO';
  }
  return 'YES';
}
class SegTree {
  constructor(n) {
    this.n = n;
    this.root = this._newNode();
    this.update = (x, z) => {
      x = Math.max(x, 0);
      x = Math.min(x, n);
      this._update(this.root, 0, n, x, z);
    };
    this.max = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._queryMax(this.root, 0, n, x, y);
    };
    this.min = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._queryMin(this.root, 0, n, x, y);
    };
  }
  _newNode(left = null, right = null) {
    return {
      left,
      right,
      max: -Infinity,
      min: Infinity
    };
  }
  _up(node) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    node.max = Math.max(left.max, right.max);
    node.min = Math.min(left.min, right.min);
  }
  _update(node, l, r, x, z) {
    if (!node) return;
    if (l === r) {
      node.max = z;
      node.min = z;
      return;
    }
    const mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    if (x <= mid) this._update(node.left, l, mid, x, z);else this._update(node.right, mid + 1, r, x, z);
    this._up(node);
  }
  _queryMax(node, l, r, x, y) {
    if (y < x) return -Infinity;
    if (!node) return -Infinity;
    if (l === x && r === y) return node.max;
    let res = 0,
        mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    if (y <= mid) res = this._queryMax(node.left, l, mid, x, y);else if (x > mid) res = this._queryMax(node.right, mid + 1, r, x, y);else res = Math.max(this._queryMax(node.left, l, mid, x, mid), this._queryMax(node.right, mid + 1, r, mid + 1, y));
    this._up(node);
    return res;
  }
  _queryMin(node, l, r, x, y) {
    if (y < x) return Infinity;
    if (!node) return Infinity;
    if (l === x && r === y) return node.min;
    let res = 0,
        mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    if (y <= mid) res = this._queryMin(node.left, l, mid, x, y);else if (x > mid) res = this._queryMin(node.right, mid + 1, r, x, y);else res = Math.min(this._queryMin(node.left, l, mid, x, mid), this._queryMin(node.right, mid + 1, r, mid + 1, y));
    this._up(node);
    return res;
  }
}

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

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