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

let c = 0;

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

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

  const arr = d.split(" ").map(Number);
  const min = arr.indexOf(Math.min(...arr));
  const max = arr.indexOf(Math.max(...arr));
  const ans = Math.min(
    Math.max(min + 1, max + 1),
    Math.max(arr.length - min, arr.length - max),
    min + 1 + arr.length - max,
    max + 1 + arr.length - min
  );

  console.log(ans);

  c++;
});

rl.on("close", () => {});

var n = parseInt(readline());
  while (n--) {
    var s = parseInt(readline());
    var stones = readline()
      .split(" ")
      .map((data) => +data);
    var stonesort = [].concat(stones).sort((a, b) => a - b);
    var max = stones.indexOf(stonesort[s - 1]);
    var min = stones.indexOf(stonesort[0]);
    var maxleft = stones.slice(max).length;
    var minleft = stones.slice(min).length;

    var maxright = stones.slice(0, max + 1).length;
    var minright = stones.slice(0, min + 1).length;

    var middleright = Math.max(maxright, minright);
    var middleleft = Math.max(maxleft, minleft);

    var mid = Math.min(maxright, minright);
    var midd = Math.min(maxleft, minleft);
    var middle = mid + midd;
    var ans = Math.min(middleright, middleleft, middle);
    print(ans);
  }

// A. Stone Game

var l0 = readline();
var n = +l0;
var arr = [];
for (var a = 0; a<n; a++) {
    var ignore = readline();
    arr.push(readline().split(' ').map(v => +v));
}

for (var x = 0; x< n; x++) {
    var min = Infinity;
    var max = 0;
    var aIndex;
    var bIndex;
    for (var y = 0; y< arr[x].length; y++) {
        if (arr[x][y] < min) {
            min = arr[x][y];
            aIndex = y;
        }

        if (arr[x][y] > max) {
            max = arr[x][y];
            bIndex = y;
        }
    }

    // sort index
    var temp = aIndex;
    if (aIndex > bIndex) {
        aIndex = bIndex;
        bIndex = temp;
    }

    var t1 = 0;
    // 1* Destroy the stones on the left until we destroy the smallest stone.
    // Then destroy the stones on the right, until we destroy the largest stone.
    t1 = t1 + Math.abs(0 - aIndex) + 1;
    t1 = t1 + Math.abs(arr[x].length - bIndex);

    // 2* Destroy the stones on the right until we destroy the smallest stone.
    // Then destroy the stones on the left, until we destroy the largest stone.
    // ignore it, because I ordered the indexes
    var t2 = Infinity

    // 3* Destroy the stones on the left until we destroy both stones.
    var t3 = 0
    var t3 = t3 + Math.abs(0 - bIndex) + 1;

    // 4* Destroy the stones on the right until we destroy both stones.
    var t4 = 0;
    var t4 = t4 + Math.abs(arr[x].length - aIndex);

    print(Math.min(t1,t2,t3,t4));
}

var t = parseInt(readline());

for(i = 0; i < t; i++) {
    var n = parseInt(readline());
    var a = readline().split(" ");
    var min = 0, max = 0;
    for(j = 0; j < n; j++) {
        if(a[j] == 1) min = j + 1;
        else if(a[j] == n) max = j + 1;
        if(min !== 0 && max !== 0) break;
    }
    if(n % 2 === 1 && ((min === (n + 1)/2) || (max === (n + 1)/2))) {
        print((n + 1)/2);
    }
    else {
        var left = Math.max(min, max);
        var right = Math.max(n - min + 1, n - max + 1);
        var middle;
        if(min < max) middle = min + n - max + 1;
        else middle = max + n - min + 1;
        print(Math.min(left, right, middle));
    }
}

var tc = parseInt(readline());

while(tc--) {
    var n = parseInt(readline());
    var arr = readline().split(' ').map(i => parseInt(i));

    var indexMax = arr.indexOf(Math.max(...arr));
    var indexMin = arr.indexOf(Math.min(...arr));

    var min = Math.min(indexMax, indexMin);
    var max = Math.max(indexMax, indexMin);

    var case1 = max + 1;
    var case2 = n - min;
    var case3 = min + 1 + n - max;

    print(Math.min(case1, case2, case3));
}

"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() {
  let t = parseInt(readLine()); // number of test cases

  while (t--) {
    let n = parseInt(readLine()); // number of stones

    let a = readLine()
      .split(" ")
      .map((x) => parseInt(x)); // array of power of stones

    console.log(getMoves(a));
  }
}

function getMoves(a) {
  let minPoz = 0;
  let maxPoz = 0;

  // find the least and greatest power stone
  for (let i = 1; i < a.length; i++) {
    if (a[i] > a[maxPoz]) maxPoz = i;
    if (a[i] < a[minPoz]) minPoz = i;
  }

  let stones = a.length;

  // 1st case
  let case1 = minPoz + 1 + stones - maxPoz;

  // 2nd case
  let case2 = maxPoz + 1 + stones - minPoz;

  // 3rd case
  let case3 = Math.max(minPoz, maxPoz) + 1;

  // 4th case
  let case4 = Math.max(stones - maxPoz, stones - minPoz);

  return Math.min(case1, case2, case3, case4);
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++];
        console.log(solve(lines[l++].split(' ').map(Number)));
    }
});

const solve = (l) => {
    const indexMin = l.indexOf(Math.min(...l));
    const indexMax = l.indexOf(Math.max(...l));

    const max = Math.max(indexMin, indexMax);
    const min = Math.min(indexMin, indexMax);

    // CASE 1
    const case_1 = max + 1;

    // CASE 2
    const case_2 = l.length - min;

    // case 3
    const case_3 = min + 1 + l.length - max;

    return Math.min(case_1, case_2, case_3);
};

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

let c = 0;
let found = 0;

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

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

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

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

    if (arr[i] === max) {
      found++;
    }

    if (found === 2) {
      ans = Math.min(ans, i + 1);
      break;
    }
  }

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

    if (arr[i] === max) {
      found++;
    }

    if (found === 2) {
      ans = Math.min(ans, i + 1);
      break;
    }
  }

  const firstNumber = Math.min(arr.indexOf(min), arr.indexOf(max)) + 1;
  arr.reverse();
  const secondNumber = Math.min(arr.indexOf(min), arr.indexOf(max)) + 1;
  ans = Math.min(ans, firstNumber + secondNumber);

  console.log(ans);
  c++;
});

rl.on("close", () => {});

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

process.stdin.on('data' , data=>{
    input += data;
});
process.stdin.on('end' , ()=>{
    main(input);
});

function main(input) {
    input = input.split("\n");
    let z = 0;
    let testCases = +input[z++];

    while(testCases--){
        let arrLen = +input[z++];
        let arr = input[z++].split(' ').map(x=>Number(x));

        let firstIdx = arr.indexOf(1)
        let lastIdx = arr.indexOf(arrLen);
        let maxIdx = Math.max(firstIdx, lastIdx);
        let minIdx = Math.min(firstIdx, lastIdx);

        let option1 = (arrLen - maxIdx) + minIdx + 1;
        let option2 = minIdx + (maxIdx - minIdx) + 1;
        let option3 = (arrLen - maxIdx) + (arrLen - minIdx - (arrLen - maxIdx));

        console.log(Math.min(option1, option2, option3));
    }
}

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

process.stdin.on('data' , data=>{
    input += data;
});
process.stdin.on('end' , ()=>{
    main(input);
});

function main(input) {
    input = input.split("\n");
    let z = 0;
    let testCases = +input[z++];

    while(testCases--){
        let arrLen = +input[z++];
        let arr = input[z++].split(' ').map(x=>Number(x));

        let firstIdx = arr.indexOf(1);
        let lastIdx = arr.indexOf(arrLen);
        let maxIdx = Math.max(firstIdx, lastIdx);
        let minIdx = Math.min(firstIdx, lastIdx);

        let option1 = (arrLen - maxIdx) + minIdx + 1;
        let option2 = minIdx + (maxIdx - minIdx) + 1;
        let option3 = (arrLen - maxIdx) + (arrLen - minIdx - (arrLen - maxIdx));

        console.log(Math.min(option1, option2, option3));
    }
}

'use strict';

function solve(n, a) {
  const min = Math.min(...a),
        max = Math.max(...a);
  let mi = a.findIndex(num => num === min),
      ma = a.findIndex(num => num === max);
  if (mi > ma) [mi, ma] = [ma, mi];
  return Math.min(ma + 1, n - mi, mi + 1 + n - ma);
}

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

let q = '';
process.stdin.on('data', c => q += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = q.split(EOL);
    var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var k = lines[i].split(' ').map(Number);
            var max = 0, min = 110000000000;
            for(j = 0; j < n; j++){
                max = Math.max(max, k[j]);
                min = Math.min(min, k[j]);
            }
            var lma = 0, lmi = 0;
            for(j = 0; j < n; j++){
                if(k[j] == max){
                    lma = j + 1;
                }
                if(k[j] == min){
                    lmi = j + 1;
                }
            }
            var rma = n - lma + 1;
            var rmi = n - lmi + 1;
            var a1 = Math.max(rma, rmi);
            var a2 = Math.max(lma, lmi);
            var a3 = Math.min(lma + rmi, rma + lmi);
            console.log(Math.min(a1, Math.min(a2, a3)));
        }
    }
});

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let input = '';
process.stdin.on('data', inputStdin => {
    input += inputStdin;
});
process.stdin.on('end', _ => {
    main(input);
});

function main(input) {
    var args = input.split("\n");
    const t = parseInt(args[0], 10);
    for (var i = 1; i <= t; i++) {
        var n = parseInt(args[2 * i - 1], 10);
        var v = args[2 * i].split(" ").map((n) => parseInt(n, 10));
        var a = 0, b = 0;
        for (var j = 0; j < n; j++) {
            if (v[j] == 1) {
                a = j;
            }
            if (v[j] == n) {
                b = j;
            }
        }
        var c = Math.min(a, b) + 1;
        var d = Math.max(a, b) + 1;
        console.log(Math.min(d, n - c + 1, c + n - d + 1));
    }
}

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

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i < t; i++){
		let m = nl.num();
		let a = nl.nums();
		let mi = a.indexOf(1);
		let ma = a.indexOf(m);
		let r = [mi + 1, ma + 1, Math.abs(mi - ma), m - mi, m - ma];
		r.sort((a, b) => a - b);
		ans.push(r[0] + r[1]);

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

process.stdin.on('end', sol);

process.stdin.resume();
process.stdin.setEncoding("utf8");
let standardInputString = "";
let currentLine = 0;
function readLine() {
  return standardInputString[currentLine++];
}
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function main() {
  const numArray = (a) => a.split(" ").map((line) => +line),
    cl = console.log,
    rl = readLine,
    tc = rl();

  for (let i = 0; i < tc; i++) {
    let n = rl();
    let array = numArray(rl());
    let step = 0;

    let greatest = array.indexOf(Math.max(...array)) + 1;
    let least = array.indexOf(Math.min(...array)) + 1;
    let i = 0;

    let dleft = Math.max(least, greatest);
    let dright = Math.max(n - greatest, n - least) + 1;

    let dleftRight = n - greatest + least + 1;
    let drightLeft = greatest + (n - least) + 1;

    console.log(Math.min(dleft, dright, drightLeft, dleftRight));
  }
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function div(a, b) {
   return Math.floor(a / b);
}

function solve() {
   var n = Number(read());
   var arr = readArray((a, i) => [Number(a), i]);
   arr.sort((a, b) => a[0] - b[0]);
   var i1 = arr[0][1];
   var i2 = arr[n - 1][1];
   if (i1 > i2) {
      var temp = i1;
      i1 = i2;
      i2 = temp;
   }
   var ans1 = n - i2 + i1 + 1;
   var ans2 = i2 + 1;
   var ans3 = n - i1;
   write(Math.min(ans1, Math.min(ans2, ans3)));
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

let lineContent = ''

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

    const testNumbers = parseInt(lines[0]);

    for (let i = 0; i < testNumbers; i++) {
        const [n] = lines[1 + i * 2].split(" ").map((e) => parseInt(e));
        const arr = lines[2 + i * 2].split(" ").map(e => parseInt(e));

        console.log(f(n, arr));
    }

})

const f = (n, arr) => {
    let max = 0, min = 0;
    for (let i = 0; i < n; i++) {
        const curr = arr[i];
        if (arr[max] < curr) {
            max = i;
        }
        if (arr[min] > curr) {
            min = i;
        }
    }

    const a = max > min ? max : min;
    const b = max > min ? min : max;

    return Math.min(a + 1, n - b, b + 1 + n - a);
}

//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 if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
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();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var output = 1 << 30;
		var L = list.indexOf(1);
		var R = list.indexOf(N);
		if(L > R){
			var tmp = L;
			L = R;
			R = tmp;
		}
		output = Math.min(output, R + 1);
		output = Math.min(output, N - L);
		output = Math.min(output, L + (N - R) + 1);
		myout(output);
	}
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        console.log(solve(lines[l++].split(' ').map(Number)));
    }
});

function solve(nums) {
    const max = Math.max(...nums)
    const min = Math.min(...nums)
    let a = nums.indexOf(max)
    let b = nums.indexOf(min)
    if (a > b) {
        const t = a
        a = b
        b = t
    }

    const t1 = b + 1
    const t2 = nums.length - a
    const t3 = a + 1 + nums.length - b
    const t4 = nums.length - a + b + 1
    return Math.min(t1, t2, t3, t4)
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));
  var min = 101;
  var a;
  var max = -1;
  var b;

  a.forEach((el, i) => {
    if (el > max) {
      max = el;
      a = i;
    }
    if (el < min) {
      min = el;
      b = i;
    }
  })

  if (b < a) {
    var tt = a;
    a = b;
    b = tt;
  }

  print(Math.min(b + 1, n - a, n - b + a + 1));
}

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var x = +readline();
    var nums = readNumArray();
    var maxInd = 0;
    var minInd = 0;
    for (var j = 1; j < x; j++) {
      if (nums[j] > nums[maxInd]) {
        maxInd = j;
      }
      if (nums[j] < nums[minInd]) {
        minInd = j;
      }
    }

    var mnInd = maxInd > minInd ? minInd : maxInd;
    var mxInd = maxInd < minInd ? minInd : maxInd
    var n12 = mxInd - mnInd - 1;
    var n1 = mnInd;
    var n2 = nums.length - mxInd - 1;
    var max = Math.max(n1, n2, n12);
    print(nums.length - max);
  }
}

main();

var numberOfCases = Number(readline());
for (var i = 0; i < numberOfCases; ++i) {
    processCase();
}

function processCase() {
    var numsCount = Number(readline());
    var nums = readline().split(" ").map(x => Number(x));

    var indicies = [0, 0];
    for (var i = 0; i < nums.length; ++i) {
        if (nums[i] < nums[indicies[0]]) {
            indicies[0] = i;
        }

        if (nums[i] > nums[indicies[1]]) {
            indicies[1] = i
        }
    }

    if (indicies[0] > indicies[1]) {
        var tmp = indicies[0];
        indicies[0] = indicies[1];
        indicies[1] = tmp;
    }

    var distances = [
        indicies[0] + 1,
        nums.length - indicies[1]
    ];

    var indexDistance = indicies[1] - indicies[0];
    print(Math.min(distances[0] + indexDistance, distances[1] + indexDistance, distances[0] + distances[1]))
}

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

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

function main() {
  let t = parseInt(readLine()); // number of test cases

  while (t--) {
    let n = parseInt(readLine()); // number of stones

    let a = readLine()
      .split(" ")
      .map((x) => parseInt(x)); // array of power of stones

    console.log(getMoves(a));
  }
}

function getMoves(a) {
  let minPoz = 0;
  let maxPoz = 0;

  // find the least and greatest power stone
  for (let i = 1; i < a.length; i++) {
    if (a[i] > a[maxPoz]) maxPoz = i;
    if (a[i] < a[minPoz]) minPoz = i;
  }

  let stones = a.length;

  // 1st case
  let case1 = minPoz + 1 + stones - maxPoz;

  // 2nd case
  let case2 = maxPoz + 1 + stones - minPoz;

  // 3rd case
  let case3 = Math.max(minPoz, maxPoz);

  return Math.min(case1, case2, case3);
}

"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() {
  let t = parseInt(readLine()); // number of test cases

  while (t--) {
    let n = parseInt(readLine()); // number of stones

    let a = readLine()
      .split(" ")
      .map((x) => parseInt(x)); // array of power of stones

    console.log(getMoves(a));
  }
}

function getMoves(a) {
  let minPoz = 0;
  let maxPoz = 0;

  // find the least and greatest power stone
  for (let i = 1; i < a.length; i++) {
    if (a[i] > a[maxPoz]) maxPoz = i;
    if (a[i] < a[minPoz]) minPoz = i;
  }

  if (minPoz <= Math.abs(a.length / 2) && maxPoz <= Math.abs(a.length / 2))
    return Math.max(minPoz + 1, maxPoz + 1);

  if (minPoz >= Math.abs(a.length / 2) && maxPoz >= Math.abs(a.length / 2))
    return Math.max(a.length - minPoz, a.length - maxPoz);

  if (
    (minPoz <= Math.abs(a.length / 2) && maxPoz >= Math.abs(a.length / 2)) ||
    (minPoz >= Math.abs(a.length / 2) && maxPoz <= Math.abs(a.length / 2))
  ) {
    return (
      Math.min(minPoz + 1, maxPoz + 1) +
      Math.min(a.length - minPoz, a.length - maxPoz)
    );
  }
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        console.log(solve(lines[l++].split(' ').map(Number)));
    }
});

const solve = (l) => {
    let lowest = l.indexOf(Math.min(...l)) + 1;
    let highest = l.indexOf(Math.max(...l)) + 1;

    const mid = Math.ceil(l.length/2);
    console.log(lowest, highest, mid);

    let num = Number.POSITIVE_INFINITY;

    // CASE 1
    num = Math.min(num, Math.max(lowest, highest));

    // CASE 2
    const reveseL = l.reverse();
    let rightLowest = reveseL.indexOf(Math.min(...reveseL)) + 1 ;
    let rightHighest = reveseL.indexOf(Math.max(...reveseL)) + 1;
    num = Math.min(num, Math.max(rightLowest, rightHighest));

    // case 3
    const left = Math.min(lowest, rightLowest);
    const right = Math.min(highest, rightHighest);

    num = Math.min(num, left +  right);

    return num;
};

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));
  var min = 101;
  var a;
  var max = -1;
  var b;

  a.forEach((el, i) => {
    if (el > max) {
      max = el;
      a = i;
    }
    if (el < min) {
      min = el;
      b = i;
    }
  })

  if (b < a) {
    var tt = a;
    a = b;
    b = tt;
  }

  var ans;
  var mid = parseInt((n - 1) / 2);

  if ((a < mid && b < mid) || (a > mid && b > mid)) {
    ans = Math.min(Math.max(a, b), n - 1- Math.min(a, b)) + 1;
  }
  else {
    ans = Math.min(a + n - b + 1, b + 1, n - a + 1);
  }

  print(ans);

}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));
  var min = 101;
  var a;
  var max = -1;
  var b;

  a.forEach((el, i) => {
    if (el > max) {
      max = el;
      a = i;
    }
    if (el < min) {
      min = el;
      b = i;
    }
  })

  if (b < a) {
    var tt = a;
    a = b;
    b = tt;
  }

  var ans;
  var mid = parseInt((n - 1) / 2);

  if ((a < mid && b < mid) || (a > mid && b > mid)) {
    ans = Math.min(Math.max(a, b), n - 1- Math.min(a, b)) + 1;
  }
  else {
    var r = Math.min((b - a), (n - b));
    ans = a + (r > 0? r + 1 : r);
  }

  print(ans);

}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));
  var min = 101;
  var a;
  var max = -1;
  var b;

  a.forEach((el, i) => {
    if (el > max) {
      max = el;
      a = i;
    }
    if (el < min) {
      min = el;
      b = i;
    }
  })

  if (b < a) {
    var tt = a;
    a = b;
    b = tt;
  }

  var ans;
  var mid = parseInt((n - 1) / 2);

  if ((a < mid && b < mid) || (a > mid && b > mid)) {
    ans = Math.min(Math.max(a, b) + 1, n - Math.max(a, b) + 1);
  }
  else {
    var r = Math.min((b - a), (n - b));
    ans = a + (r > 0? r + 1 : r);
  }

  print(ans);

}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));
  var min = 101;
  var a;
  var max = -1;
  var b;

  a.forEach((el, i) => {
    if (el > max) {
      max = el;
      a = i;
    }
    if (el < min) {
      min = el;
      b = i;
    }
  })

  if (b < a) {
    var tt = a;
    a = b;
    b = tt;
  }

  var ans;
  var mid = parseInt((n - 1) / 2);

  if ((a < mid && b < mid) || (a > mid && b > mid))
    ans = Math.min(Math.max(a, b) + 1, n - Math.max(a, b) + 1);
  else
    ans = a + Math.min((b - a), (n - b)) + 1;

  print(ans);

}

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var x = +readline();
    var nums = readNumArray();
    var maxInd = nums[0];
    var minInd = nums[0];
    for (var j = 0; j < x; j++) {
      if (nums[j] > nums[maxInd]) {
        maxInd = j;
      }
      if (nums[j] < nums[minInd]) {
        minInd = j;
      }
    }

    var mnInd = maxInd > minInd ? minInd : maxInd;
    var mxInd = maxInd < minInd ? minInd : maxInd
    var n12 = mxInd - mnInd - 1;
    var n1 = mnInd;
    var n2 = nums.length - mxInd - 1;
    var max = Math.max(n1, n2, n12);
    print(nums.length - max);
  }
}

main();

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var x = +readline();
    var nums = readNumArray();
    var maxInd = nums[0];
    var minInd = nums[0];
    for (var j = 0; j < x; j++) {
      if (nums[j] > nums[maxInd]) {
        maxInd = j;
      }
      if (nums[j] < nums[minInd]) {
        minInd = j;
      }
    }

    var mnInd = maxInd > minInd ? minInd : maxInd;
    var mxInd = maxInd < minInd ? minInd : maxInd
    var n12 = mxInd - mnInd;
    var n1 = mnInd + 1;
    var n2 = Math.abs(nums.length - mxInd);
    var max = Math.max(n1, n2, n12);
    print(nums.length - max + 1);;
  }
}
main();

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var x = +readline();
    var nums = readNumArray();
    var maxInd = nums[0];
    var minInd = nums[0];
    for (var j = 0; j < x; j++) {
      if (nums[j] > nums[maxInd]) {
        maxInd = j;
      }
      if (nums[j] < nums[minInd]) {
        minInd = j;
      }
    }

    var mnInd = maxInd > minInd ? minInd : maxInd;
    var mxInd = maxInd < minInd ? minInd : maxInd
    var n12 = Math.abs(mxInd - mnInd - 1);
    var n1 = mnInd;
    var n2 = Math.abs(nums.length - mxInd - 1);
    var max = Math.max(n1, n2, n12);
    print(nums.length - max);;
  }

}

main();

var numberOfCases = Number(readline());
for (var i = 0; i < numberOfCases; ++i) {
    processCase();
}

function processCase() {
    var numsCount = Number(readline());
    var nums = readline().split(" ").map(x => Number(x));

    var indicies = [0, 0];
    for (var i = 0; i < nums.length; ++i) {
        if (nums[i] < nums[indicies[0]]) {
            indicies[0] = i;
        }

        if (nums[i] > nums[indicies[1]]) {
            indicies[1] = i
        }
    }

    indicies.sort();
    var distances = [
        indicies[0] + 1,
        nums.length - indicies[1]
    ];

    var indexDistance = indicies[1] - indicies[0];
    print(Math.min(distances[0] + indexDistance, distances[1] + indexDistance, distances[0] + distances[1]))
}


  var n = parseInt(readline());
  var last = Infinity;
  var res = 'maybe';
  for(var i = 0; i < n; i += 1) {
    var tmp = readline().split(' ').map(x => parseInt(x));
    if(tmp[0] !== tmp[1]) {
      res = 'rated';
    }
    if(res === 'maybe') {
      if(tmp[0] > last) {
        res = 'unrated'
      }
    }
    last = tmp[0];
  }
  print(res);

var number = readline();
var formerStandings = [];
var nextStandings = [];
var flag2 = true;
for(var i=0; i<number; i++) {
    var line = readline().split(" ");
    formerStandings.push(parseInt(line[0]));
    if(line[0]!=line[1])
    flag2 = false;
}
var flag = true;
for(var i=0;i<number-1;i++) {
    if(Math.min(formerStandings[i],formerStandings[i+1])!=formerStandings[i+1])
    flag=  false;
}

if(!flag2)
print("rated");
else if(flag)
print("maybe");
else
print("unrated");

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

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

function write(x) {
    process.stdout.write(x);
}

function array2d(r,c) {
    let ans =[];
    for(let i = 0; i < r; i++) {
        let rowElements = [];
        for(let j = 0; j < c; j++) {
            rowElements.push(0);
        }
        ans.push(rowElements);
    }
    return ans;
}
function max(a,b){
    if(a > b) return a;
    else return b;
}
function main() {
    let [n] = readint();
    let changed = false;
    let sorted = true;
    let [prevA,prevB] = [5000,5000];
    while(n--) {
        let [a,b] = readint();
        if(a != b) changed = true;
        if(prevA < a) sorted = false;
        prevA = a;
        prevB = b;
    }
    if(changed) print("rated");
    else if(!sorted) print("unrated");
    else print("maybe");

}

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

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

  const [a, b] = d.split(' ').map(Number);

  if (b > a) {
    ans = 'rated';
  }

  if (a !== b) {
    ans = 'rated';
  }

  if (prev < a && ans !== 'rated') {
    ans = 'unrated';
  }
  else {
    prev = a;
  }

  c++;
});

rl.on('close', () => {
  console.log(ans);
});

 function cal() {
        var n = +readline();
        var temp = 0;
        var maybe = true;
        var res = '';
        for (var i = 0; i < n; i++) {
            var token = readline().split(' ');
            var numA = +token[0];
            var numB = +token[1];

            if (numA != numB) {
                print("rated");
                return;
            }

            if (temp != 0 && numA > temp)
                maybe = false;
            temp = numA;

        }

        if (maybe)
            print("maybe");
        else
            print("unrated");

    }
    cal();

var rounds = parseInt(readline());

var rated = false;
var unrated = false;

var before;
var after;

for (var i = 0; i < rounds; i++) {
    var values = readline().split(" ").map(Number);
    if (values[0] > before || values[1] > after) {
        unrated = true;
    }

    before = values[0];
    after = values[1];

    if (before !== after) {
        rated = true;
        break;
    }
}

if (rated) {
    print('rated');
} else if (unrated) {
    print('unrated');
} else {
    print('maybe');
}

var number = readline();
var formerStandings = [];
var nextStandings = [];
var flag2 = true;
for(var i=0; i<number; i++) {
    var line = readline().split(" ");
    formerStandings.push(parseInt(line[0]));
    if(line[0]!=line[1])
    flag2 = false;
}
var flag = true;
if(formerStandings.reduce(function(x,y){return Math.min(x,y)})!=formerStandings[number-1])
    flag = false;

if(!flag2)
print("rated");
else if(flag)
print("maybe");
else
print("unrated");

var number = readline();
var formerStandings = [];
var nextStandings = [];
var flag2 = true;
for(var i=0; i<number; i++) {
    var line = readline().split(" ");
    formerStandings.push(parseInt(line[0]));
    if(line[0]!=line[1])
    flag2 = false;
}
var flag = true;
for(var i=0;i<number-1;i++) {
    if(Math.min(formerStandings[i],formerStandings[i+1]!=formerStandings[i+1]))
    flag=  false;
}

if(!flag2)
print("rated");
else if(flag)
print("maybe");
else
print("unrated");

var n = +readline();
        var temp = 0;
        var maybe = true;
        var res ='';
        for (var i = 0; i < n; i++) {
            var token = readline().split(' ');
            var numA = token[0];
            var numB = token[1];

            if (numA != numB) {
                res = "rated";
            }

            if (temp != 0 && numA > temp)
                maybe = false;
            temp = numA;

        }
        if (res != '') {
            print(res);

        } else
        if (maybe)
            print("maybe");
        else
            print("unrated");

function cal() {
        var n = +readline();
        var temp = 0;
        var maybe = true;
        var res = '';
        for (var i = 0; i < n; i++) {
            var token = readline().split(' ');
            var numA = token[0];
            var numB = token[1];

            if (numA != numB) {
                print("rated");
                return;
            }

            if (temp != 0 && numA > temp)
                maybe = false;
            temp = numA;

        }

        if (maybe)
            print("maybe");
        else
            print("unrated");

    }
    cal();

function cal() {
        var n = +readline();
        var temp = 0;
        var maybe = true;
        var res = '';
        for (var i = 0; i < n; i++) {
            var token = readline().split(' ');
            var numA = token[0];
            var numB = token[1];

            if (numA != numB) {
                res = "rated";
                return;
            }

            if (temp != 0 && numA > temp)
                maybe = false;
            temp = numA;

        }

        if (maybe)
            print("maybe");
        else
            print("unrated");

    }
    cal();

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

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

  const [a, b] = d.split(' ').map(Number);

  if (b > a) {
    ans = 'rating';
  }

  if (prev < a) {
    ans = 'unrated';
  }
  else {
    prev = a;
  }

  c++;
});

rl.on('close', () => {
  console.log(ans);
});

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

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

  const [a, b] = d.split(' ').map(Number);

  if (b > a) {
    ans = 'rating';
  }

  if (prev < a && ans !== 'rating') {
    ans = 'unrated';
  }
  else {
    prev = a;
  }

  c++;
});

rl.on('close', () => {
  console.log(ans);
});

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

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

  const [a, b] = d.split(' ').map(Number);

  if (b > a) {
    ans = 'rated';
  }

  if (prev < a && ans !== 'rated') {
    ans = 'unrated';
  }
  else {
    prev = a;
  }

  c++;
});

rl.on('close', () => {
  console.log(ans);
});


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

    function foo (data) {
        const [a, b, x, y] = data;
        return Math.max(b*x, a*y, a*(b-y-1), b*(a-x-1));

    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount].split(" ").map(Number);

        let result = foo(data);
        answer += result +"\n";
        testCount++;
    }
    console.log(answer);
})

let data = '';
process.stdin.on('data', input => data += input);
process.stdin.on('end', () => {
    const inputStrings = data.split('\n');
    const n = parseInt(inputStrings[0], 10);
    const place = ([a,b,x,y]) => Math.max( (a - x - 1) * b, x * b, a * (b - y - 1), a * y);
    let answ = '';
    for (let i = 1; i <= n; i++) {
        const inputArr = inputStrings[i].split(' ').map(Number);
        answ += place(inputArr)+'\n';
    }
    process.stdout.write(answ);
});

let data = '';
process.stdin.on('data', input => data += input);
process.stdin.on('end', () => {
    const inputStrings = data.split('\n');
    const n = parseInt(inputStrings[0], 10);
    const place = ([a,b,x,y]) => Math.max( (a - x - 1) * b, x * b, a * (b - y - 1), a * y);
    for (let i = 1; i <= n; i++) {
        const inputArr = inputStrings[i].split(' ').map(Number);
        process.stdout.write( place(inputArr)+'\n' );
    }
});

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

let c = 0;

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

  const [a, b, x, y] = d.split(" ").map(Number);
  const ans = Math.max(y * a, (b - y - 1) * a, x * b, (a - x - 1) * b);

  if (Number.isInteger(ans)) {
    console.log(ans);
  }
  c++;
});

const processData = (lines) => {
  const num = +lines[0]

  for (let j=0; j<num; j++){
    const [a, b, x, y] = lines[j+1].split(' ').map( x => +x)
    const sq = [ (a-x-1) * (b), (b-y-1) * (a), (x)*b, (y) * a ]
    console.log(Math.max.apply(null, sq));
  }
}

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

function main(rawInput) {
    var lines = rawInput.split("\n");
    var tests = parseInt(lines.shift(), 10);
    for (var i = 0; i < tests; i++) {
        var _a = lines.shift().split(" ").map(function (v) { return parseInt(v, 10); }), w = _a[0], h = _a[1], x = _a[2], y = _a[3];
        console.log(solve(w, h, x, y));
    }
}
function solve(w, h, x, y) {
    return [
        w * (y),
        w * (h - (y + 1)),
        h * (x),
        h * (w - (x + 1))
    ].reduce(function (a, v) { return a > v ? a : v; });
}
(function () {
    var s = "";
    process.stdin.on("data", function (d) { return s += d; });
    process.stdin.on("end", function () { return main(s); });
})();

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

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	let t = nl.num();
    let r = [];
    for(let i = 0; i < t; i++) {
        let [a, b, x, y] = nl.nums();
        let mx = Math.max(x, a - x - 1) * b;
        let my = Math.max(y, b - y - 1) * a;
        r.push(Math.max(mx, my));
    }
    console.log(r.join('\n'));
};

process.stdin.on('end', sol);

const getSquare = ([a, b, x, y]) => Math.max(
  x * b,
  (a - (x + 1)) *b,
  a * y,
  a * (b - (y + 1))
);

const main = (data) => {
  const n = +data[0];

  for (let i = 1; i <= n; i++) {
    console.log(getSquare(data[i].split(' ').map(x => +x)));
  }
};

let data = '';

process.stdin.on('data', input => data += input);
process.stdin.on('end', () => {
  data = data.split('\n');

  main(data);
});

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var a = one[0];
    var b = one[1];
    var x = one[2];
    var y = one[3];
    var list = [(b - y - 1) * a, y * a, b * (a - x - 1), b * x];
    output[i] = Math.max.apply(null, list);
  }
  myout(myconv(output, 9));
}

var toInt = x =>parseInt(x);

var t = parseInt(readline());

for(var tt=0;tt<t;tt++) {
    var abxy = readline().split(' ').map(toInt);
    var c = Math.max(abxy[1]-abxy[3]-1, abxy[3]);
    var r = Math.max(abxy[0]-abxy[2]-1, abxy[2]);

    var best = Math.max(r * abxy[1], abxy[0] * c);
    print(best);
}

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let answer = '';
process.stdin.on('data', inputStdin => {
    let inputStrings = inputStdin.split('\n');
    const n = parseInt(inputStrings[0], 10);
    for (let i = 1; i < inputStrings.length; i++) {
        const inputArr = inputStrings[i].trim().split(' ');
        if (inputArr.length !== 4) break;
        answer += place(inputArr)+'\n';
    }
});
process.stdin.on('end', _ => {
    process.stdout.write( answer );
});
function place(arr) {
    let aW = 0, bW = 0, a = arr[0], b = arr[1], x = arr[2], y = arr[3];
    if (x >= y) {
        bW = b;
        if ( 0.5 * a > x ) {
            aW = a - x - 1;
        } else {
            aW = a;
        }
    } else {
        aW = a;
        if ( 0.5 * b > y ) {
            bW = b - y - 1;
        } else {
            bW = y;
        }
    }
    return aW * bW;
}

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

let c = 0;

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

  const [a, b, x, y] = d.split(" ").map(Number);
  const ans = Math.max(y * a, (b - y - 1) * a, x * b, (a - x - 1) * b);

  console.log(ans);
  c++;
});


t = +readline();
while(t--) {
  input = readline();
  res = input.length;
  mn = 0;
  cur = 0;
  for(i = 0;i < input.length; i++) {
    if (input[i] === '+') {
          cur = cur + 1;
      } else
          cur = cur - 1;
      if (cur < mn) {
          mn = cur;
          res += i + 1;
      }
  }
  print(res);

}

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 => string.trim());

    main();
});

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

const s2i = s => parseInt(s, 10);

function main() {
  let T = s2i(readLine());
  let out = '';
  while (T--) {
    const s = readLine()
    let sum = 0;
    let res = 0;
    for (let i = 0, l = s.length; i < l; i++) {
      const c = s.charAt(i);
      res++;
      if (c === '+') {
        sum++;
      }
      else {
        sum--;
        if (sum < 0) {
          sum = 0;
          res += i + 1;
        }
      }
    }

    out += res + '\n'
  }
  console.log(out)
}

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

    B();
});

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

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

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

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        if(n % 2 === 0){
            console.log('YES');
        }else{
            console.log('NO');
        }
    }
}

function D(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,k] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let b = new Array(n);
        for(let i = 0; i < n; i++){
            let mod = a[i] % k;
            if(mod !== 0){
                mod = k-mod;
            }
            b[i] = [a[i], mod];
        }
        b.sort((c,d) => c[1]-d[1]);
        let count = 0;
        let x = 0;
        for(let i = 0; i < n; i++){
            if((b[i][0] + x) % k === 0){
                x += 1;
                count += 1;
            }else{
                let d = k-((b[i][0]+x)%k);
                x += d+1;
                count += d+1;
            }
        }

        console.log(count);
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let s = readline().split('');
        let res = 0;
        let x = 0;
        for(let i = 0; i < s.length; i++){
            if(s[i] === '+') x++;
            if(s[i] === '-') x--;

            if(x < 0){
                res += i+1;
                x = 0;
            }
        }

        console.log(res + s.length);
    }
}

const readline = require('readline');

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

var lineCount = 0
var testCount = 0
var outputStr = ''

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if (lineCount >= testCount) {
        outputStr += getWinner(input) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += getWinner(input) + '\n'
    }
    lineCount++
});

// console.log(getWinner('++----++-'))

function getWinner(str) {
    var sum = 0;
    var minsum = 0;
    var res = 0;
    var minindex = 0;
    for (var i = 0; i < str.length; i++) {
        if (str[i] == '+') {
            sum += 1
        }
        else {
            sum -= 1
        }
        if (sum < minsum) {
            res += i + 1
            minsum = sum
            minindex = i
        }
    }
    res += i
    return res
}

function solve() {
   var T = Number(read());
   for (var t = 0; t < T; t++) {
      var s = read();
      var sum = 0;
      var wait = -1;
      var ans = s.length;
      for (var i = 0; i < s.length; i++) {
         sum += s[i] === '+' ? 1 : -1;
         if (sum === wait) {
            ans += i + 1;
            wait--;
         }
      }
      write(ans);
   }
}

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

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

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

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

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

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

var Tc = parseInt(readline());
while (Tc-- > 0) {
  var s = readline();
  var sum = 0;
  var m = -1;
  var ans = s.length;
  for (var i = 0; i < s.length; i++) {
    sum += s[i] === "+" ? 1 : -1;
    if (sum === m) {
      ans += i + 1;
      m--;
    }
  }
  print(ans);
}

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

    B();
});

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

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

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

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        if(n % 2 === 0){
            console.log('YES');
        }else{
            console.log('NO');
        }
    }
}

function D(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,k] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let b = new Array(n);
        for(let i = 0; i < n; i++){
            let mod = a[i] % k;
            if(mod !== 0){
                mod = k-mod;
            }
            b[i] = [a[i], mod];
        }
        b.sort((c,d) => c[1]-d[1]);
        let count = 0;
        let x = 0;
        for(let i = 0; i < n; i++){
            if((b[i][0] + x) % k === 0){
                x += 1;
                count += 1;
            }else{
                let d = k-((b[i][0]+x)%k);
                x += d+1;
                count += d+1;
            }
        }

        console.log(count);
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let s = readline().split('');
        let a = new Array(10);
        let x = 0;
        for(let i = 0; i < s.length; i++){
            if(s[i] === '+')
                x += 1;
            else
                x -= 1;

            if(x < 0){
                if(a[-1*x-1] === undefined)
                    a[-1*x-1] = i+1;
            }
        }

        let res = 0;
        for(let i = 0; i < Math.abs(x); i++){
            if(a[i])
                res += a[i];
        }

        console.log(res + s.length);
    }
}

const readline = require('readline');

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

var lineCount = 0
var testCount = 0
var outputStr = ''

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if (lineCount >= testCount) {
        outputStr += getWinner(input) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += getWinner(input) + '\n'
    }
    lineCount++
});

// console.log(getWinner('++--+-'))

function getWinner(str) {
    var sum = 0;
    var minsum = 0;
    var res = 0;
    var minindex = 0;
    for (var i = 0; i < str.length; i++) {
        if (str[i] == '+') {
            sum += 1
        }
        else {
            sum -= 1
        }
        // console.log(minsum, sum)
        if(sum<minsum){
            minsum = sum
            minindex = i
        }
        if (sum <= minsum && sum<0) {
            res += i + 1
        }
    }
    if(minindex == str.length-1||minindex==0){
        res+=i
    }
    return res
}