You're given an array $$$a$$$ of length $$$2n$$$. Is it possible to reorder it in such way so that the sum of the first $$$n$$$ elements isn't equal to the sum of the last $$$n$$$ elements?

The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$), where $$$2n$$$ is the number of elements in the array $$$a$$$. The second line contains $$$2n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{2n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.

If there's no solution, print "-1" (without quotes). Otherwise, print a single line containing $$$2n$$$ space-separated integers. They must form a reordering of $$$a$$$. You are allowed to not change the order.

NoteIn the first example, the first $$$n$$$ elements have sum $$$2+1+3=6$$$ while the last $$$n$$$ elements have sum $$$1+1+2=4$$$. The sums aren't equal.In the second example, there's no solution.

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    };

    var n = read.number();
    var a = read.arrNumber(' ');

    var sum1 = 0;
    var sum2 = 0;
    for(var i = 0; i < n; i++) {
        sum1 += a[i];
        sum2 += a[i + n];
    }

    if(sum1 !== sum2) {
        print(a.join(' '));
        return;
    }

    var eq = true;
    for(var i = 1; i < 2 * n; i++) {
        if(a[i] !== a[i - 1]) {
            eq = false;
            break;
        }
    }

    if(eq) {
        print(-1);
        return;
    }

    for(var i = 0; i < n; i++) {
        for(var j = 0; j < n; j++) {
            if(a[i] != a[n + j]) {
                var tmp = a[i];
                a[i] = a[n + j];
                a[n + j] = tmp;
                print(a.join(' '));
                return;
            }
        }
    }

}());

var n = parseInt(readline(), 10),
    a = readline().split(' ').map(el => parseInt(el, 10)).sort((a,b) => a-b),
    sum_1 = 0,
    sum_2 = 0;

for(var i=0; i<2*n; i++) {
    if(i <= n-1) sum_1 += a[i];
    else sum_2 += a[i];
}

print(sum_1 !== sum_2 ? a.join(' ') : -1);

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

var a = readline().split(" ").map(function(x) { return parseInt(x); });
var sum = 0;
var hash = [];
var str = "";
var unique = null;
var flag = false;

if(a.length % 2 == 1) write(a.join(" "));
else {
    for(var i = 0; i < a.length; i++) {
        sum += a[i];
        if(unique === null || unique == a[i])
            unique = a[i];
        else
            flag = true;
    }

    if(sum % 2 == 1) write(a.join(" "));
    else if(!flag) write(-1);
    else {
        write(a.sort().join(" "));
    }
}

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    };

    var n = read.number();
    var a = read.arrNumber(' ');

    var sum1 = 0;
    var sum2 = 0;
    for(var i = 0; i < n; i++) {
        sum1 += a[i];
        sum2 += a[i + n];
    }

    if(sum1 !== sum2) {
        print(a.join(' '));
        return;
    }

    var eq = true;
    for(var i = 1; i < 2 * n; i++) {
        if(a[i] !== a[i - 1]) {
            eq = false;
            break;
        }
    }

    if(eq) {
        print(-1);
        return;
    }

    for(var i = 0; i < n; i++) {
        for(var j = 0; j < n; i++) {
            if(a[i] != a[n + j]) {
                var tmp = a[i];
                a[i] = a[n + j];
                a[n + j] = tmp;
                print(a.join(' '));
                return;
            }
        }
    }

}());

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

var a = readline().split(" ").map(function(x) { return parseInt(x); });
var sum = 0;
var hash = [];
var str = "";

if(a.length % 2 == 1) write(a.join(" "));
else {
    for(var i = 0; i < a.length; i++) {
        sum += a[i];
        if(hash[a[i]] == null) {
            hash[a[i]] = "0";
        }
    }

    if(sum % 2 == 1) write(a.join(" "));
    else if(hash.length <= 2) write(-1);
    else {
        write(a.sort().join(" "));
    }
}

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

var a = readline().split(" ").map(function(x) { return parseInt(x); });
var sum = 0;
var hash = [];
var str = "";

if(a.length % 2 == 1) write(a.join(" "));
else {
    for(var i = 0; i < a.length; i++) {
        sum += a[i];
        if(hash[a[i]] == null)
            hash[a[i]] = 1;
    }

    if(sum % 2 == 1) write(a.join(" "));
    else if(hash.length == 1) write(-1);
    else {
        write(a.sort().join(" "));
    }
}


You are given an array $$$a_1, a_2, \dots, a_n$$$, consisting of $$$n$$$ integers. You are also given an integer value $$$x$$$.Let $$$f(k)$$$ be the maximum sum of a contiguous subarray of $$$a$$$ after applying the following operation: add $$$x$$$ to the elements on exactly $$$k$$$ distinct positions. An empty subarray should also be considered, it has sum $$$0$$$.Note that the subarray doesn't have to include all of the increased elements.Calculate the maximum value of $$$f(k)$$$ for all $$$k$$$ from $$$0$$$ to $$$n$$$ independently.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of testcases. The first line of the testcase contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 5000$$$; $$$0 \le x \le 10^5$$$) — the number of elements in the array and the value to add. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$). The sum of $$$n$$$ over all testcases doesn't exceed $$$5000$$$.

For each testcase, print $$$n + 1$$$ integers — the maximum value of $$$f(k)$$$ for all $$$k$$$ from $$$0$$$ to $$$n$$$ independently.

NoteIn the first testcase, it doesn't matter which elements you add $$$x$$$ to. The subarray with the maximum sum will always be the entire array. If you increase $$$k$$$ elements by $$$x$$$, $$$k \cdot x$$$ will be added to the sum.In the second testcase:   For $$$k = 0$$$, the empty subarray is the best option.  For $$$k = 1$$$, it's optimal to increase the element at position $$$3$$$. The best sum becomes $$$-1 + 5 = 4$$$ for a subarray $$$[3, 3]$$$.  For $$$k = 2$$$, it's optimal to increase the element at position $$$3$$$ and any other element. The best sum is still $$$4$$$ for a subarray $$$[3, 3]$$$.  For $$$k = 3$$$, you have to increase all elements. The best sum becomes $$$(-2 + 5) + (-7 + 5) + (-1 + 5) = 5$$$ for a subarray $$$[1, 3]$$$.

'use strict';

function solve(n, m, a) {
  const c = new Array(n).fill(-Infinity);
  for (let i = 0; i < n; i++) {
    let sum = 0;
    for (let j = i; j < n; j++) {
      sum += a[j];
      c[j - i] = Math.max(c[j - i], sum);
    }
  }
  const res = new Array(n + 1).fill(-Infinity);
  res[0] = Math.max(0, ...c);
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      res[i + 1] = Math.max(0, res[i + 1], (Math.min(i, j) + 1) * m + c[j]);
    }
  }
  return 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, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

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

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

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

const mxN = 5005;
const INF = 1e9;

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

		const sums = Array(n+1).fill(-INF); sums[0] = 0;
		for (let i = 0; i < n; i++) {
			for (let j = i, sum = 0; j < n; j++) {
				sum += a[j];
				sums[j-i+1] = Math.max(sums[j-i+1], sum);
			}
		}

		const ans = Array(n+1).fill(0);
		for (let k = 0; k <= n; k++) {
			for (let i = 0; i <= n; i++) {
				ans[k] = Math.max(ans[k], sums[i]+Math.min(i, k)*x);
			}
		}

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

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

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

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

const mxN = 5005;
const INF = 1e10;

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

		const psum = []; psum[-1] = 0;
		for (let i = 0; i < n; i++) psum[i] = psum[i-1]+a[i];

		const sums = Array(n+1).fill(-INF);
		for (let i = 0; i <= n; i++) {
			for (let j = 0; j+i-1 < n; j++) {
				sums[i] = Math.max(sums[i], psum[j+i-1]-psum[j-1]);
			}
		}

		const ans = Array(n+1).fill(0);
		for (let k = 0; k <= n; k++) {
			for (let i = 0; i <= n; i++) {
				ans[k] = Math.max(ans[k], sums[i]+Math.min(i, k)*x);
			}
		}

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

const readline = require('readline')

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

function solve(n, x, arr) {
    const dp = Array(n + 1).fill(-Infinity)
    dp[0] = 0
    for (let i = 0; i < n; i++) {
        let s = 0
        for (let j = i; j < n; j++) {
            s += arr[j]
            //
            const l = j - i + 1
            dp[l] = Math.max(dp[l], s)
        }
    }
    // console.log(dp)
    const ans = Array(n + 1).fill(-Infinity)
    for (let i = 0; i <= n; i++) {
        for (let l = i; l <= n; l++) {
            ans[i] = Math.max(ans[i], dp[l] + Math.min(l, i) * x)
            if (i) {
                ans[i] = Math.max(ans[i - 1], ans[i])
            }
        }
    }
    return ans.join(' ')
}

'use strict';

function solve(n, m, a) {
  const c = new Array(n).fill(-Infinity);
  for (let i = 0; i < n; i++) {
    let sum = 0;
    for (let j = i; j < n; j++) {
      sum += a[j];
      c[j - i] = Math.max(c[j - i], sum);
    }
  }
  const res = new Array(n + 1).fill(-Infinity);
  res[0] = Math.max(0, ...c);
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      res[i + 1] = Math.max(res[i + 1], (Math.min(i, j) + 1) * m + c[j]);
    }
  }
  return 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, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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


The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.During the registration, the organizers asked each of the n participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size:   the size he wanted, if he specified one size;  any of the two neibouring sizes, if he specified two sizes. If it is possible, the program should find any valid distribution of the t-shirts.

The first line of the input contains six non-negative integers — the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100 000. The second line contains positive integer n (1 ≤ n ≤ 100 000) — the number of participants. The following n lines contain the sizes specified by the participants, one line per participant. The i-th line contains information provided by the i-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring.

If it is not possible to present a t-shirt to each participant, print «NO» (without quotes). Otherwise, print n + 1 lines. In the first line print «YES» (without quotes). In the following n lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input. If there are multiple solutions, print any of them.

var calcDistr = function ( hist, pref ) {
  var i,
    j,
    pi,
    distr,
    given;

  given = 0;
  distr = [];
  for ( i = 0; i < pref.length; ++i ) {
   pi = pref[ i ];
   if ( pi.length !== 1 ) {
     continue;
   }
   if ( hist[ pi[ 0 ] ] === 0 ) {
     return;
   }
   distr[ i ] = pi[ 0 ];
   ++given;
   --hist[ pi[ 0 ] ];
  }

  for ( var size of Object.getOwnPropertyNames( hist ) ) {
    for ( j = 1; j >= 0; --j ) {
      for ( i = 0; i < pref.length; ++i ) {
        pi = pref[ i ];
        if ( pi.length !== 2 || pi[ j ] !== size || distr[ i ] != null  ) {
          continue;
        }
        if ( hist[ pi[ j ] ] > 0 ) {
          distr[ i ] = pi[ j ];
          ++given;
          --hist[ pi[ j ] ];
        }
      }
    }
  }

  if ( given === pref.length ) {
    return distr;
  }
};

var input = readline().split( " " ).map( b => parseInt( b, 10 ) );
var hist = { "S": input[0], "M": input[1], "L": input[2], "XL": input[3], "XXL": input[4], "XXXL": input[5]};
readline();
var line,
  pref;
pref = [];
while ( line = readline() ) {
  pref.push( line.split( "," ) );
}

var result = calcDistr( hist, pref );
if ( result ) {
  print( "YES" );
  print( result.join( "\n" ) );
} else {
  print( "NO" );
}

// Greedy solution, O(n) runtime and O(n) memory.

var calcDistr = function ( hist, pref ) {
  var varPrefHist,
    i,
    pi,
    distr;

  distr = [];
  for ( i = 0; i < pref.length; ++i ) {
   pi = pref[ i ];
   if ( pi.length !== 1 ) {
     continue;
   }
   if ( hist[ pi[ 0 ] ] === 0 ) {
     return;
   }
   distr[ i ] = pi[ 0 ];
   --hist[ pi[ 0 ] ];
  }

  varPrefHist = { "S": 0, "M": 0, "L": 0, "XL": 0, "XXL": 0, "XXXL": 0};
  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }
    ++varPrefHist[ pi[ 0 ] ];
    ++varPrefHist[ pi[ 1 ] ];
  }

  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }
    // Greedy choise. Choose one that in least demand.
    if ( ( varPrefHist[ pi[ 0 ] ] >= varPrefHist[ pi[ 1 ] ] || hist[ pi[ 0 ] ] === 0 ) && hist[ pi[ 1 ] ] > 0 ) {
      distr[ i ] = pi[ 1 ];
      --hist[ pi[ 1 ] ];
    } else if ( ( varPrefHist[ pi[ 0 ] ] < varPrefHist[ pi[ 1 ] ] || hist[ pi[ 1 ] ] === 0 ) && hist[ pi[ 0 ] ] > 0 ) {
      distr[ i ] = pi[ 0 ];
      --hist[ pi[ 0 ] ];
    }  else {
      return;
    }
  }

  return distr;
};

var input = readline().split( " " ).map( b => parseInt( b, 10 ) );
var hist = { "S": input[0], "M": input[1], "L": input[2], "XL": input[3], "XXL": input[4], "XXXL": input[5]};
readline();
var line,
  pref;
pref = [];
while ( line = readline() ) {
  pref.push( line.split( "," ) );
}

var result = calcDistr( hist, pref );
if ( result ) {
  print( "YES" );
  print( result.join( "\n" ) );
} else {
  print( "NO" );
}

var calcDistr = function ( hist, pref ) {
  var i,
    pi,
    distr;

  distr = [];
  for ( i = 0; i < pref.length; ++i ) {
   pi = pref[ i ];
   if ( pi.length !== 1 ) {
     continue;
   }
   if ( hist[ pi[ 0 ] ] === 0 ) {
     return;
   }
   distr[ i ] = pi[ 0 ];
   --hist[ pi[ 0 ] ];
  }

  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }

    if ( hist[ pi[ 0 ] ] > 0 ) {
      distr[ i ] = pi[ 0 ];
      --hist[ pi[ 0 ] ];
    } else if ( hist[ pi[ 1 ] ] > 0 ) {
      distr[ i ] = pi[ 1 ];
      --hist[ pi[ 1 ] ];
    } else {
      return;
    }
  }

  return distr;
};

var input = readline().split( " " ).map( b => parseInt( b, 10 ) );
var hist = { "S": input[0], "M": input[1], "L": input[2], "XL": input[3], "XXL": input[4], "XXXL": input[5]};
readline();
var line,
  pref;
pref = [];
while ( line = readline() ) {
  pref.push( line.split( "," ) );
}

var result = calcDistr( hist, pref );
if ( result ) {
  print( "YES" );
  print( result.join( "\n" ) );
} else {
  print( "NO" );
}

// Greedy solution, O(n) runtime and O(n) memory.

var calcDistr = function ( hist, pref ) {
  var varPrefHist,
    i,
    pi,
    distr;

  distr = [];
  for ( i = 0; i < pref.length; ++i ) {
   pi = pref[ i ];
   if ( pi.length !== 1 ) {
     continue;
   }
   if ( hist[ pi[ 0 ] ] === 0 ) {
     return;
   }
   distr[ i ] = pi[ 0 ];
   --hist[ pi[ 0 ] ];
  }

  varPrefHist = { "S": 0, "M": 0, "L": 0, "XL": 0, "XXL": 0, "XXXL": 0};
  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }
    ++varPrefHist[ pi[ 0 ] ];
    ++varPrefHist[ pi[ 1 ] ];
  }

  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }
    // Greedy choise. Choose one that in least demand.
    if ( ( varPrefHist[ pi[ 0 ] ] >= varPrefHist[ pi[ 1 ] ] || hist[ pi[ 0 ] ] === 0 ) && hist[ pi[ 1 ] ] > 0 ) {
      distr[ i ] = pi[ 1 ];
      --hist[ pi[ 1 ] ];
    } else if ( ( varPrefHist[ pi[ 0 ] ] < varPrefHist[ pi[ 1 ] ] || hist[ pi[ 1 ] ] ) && hist[ pi[ 0 ] ] > 0 ) {
      distr[ i ] = pi[ 0 ];
      --hist[ pi[ 0 ] ];
    }  else {
      return;
    }
  }

  return distr;
};

var input = readline().split( " " ).map( b => parseInt( b, 10 ) );
var hist = { "S": input[0], "M": input[1], "L": input[2], "XL": input[3], "XXL": input[4], "XXXL": input[5]};
readline();
var line,
  pref;
pref = [];
while ( line = readline() ) {
  pref.push( line.split( "," ) );
}

var result = calcDistr( hist, pref );
if ( result ) {
  print( "YES" );
  print( result.join( "\n" ) );
} else {
  print( "NO" );
}

// Greedy solution, O(n) runtime and O(n) memory.

var calcDistr = function ( hist, pref ) {
  var varPrefHist,
    i,
    pi,
    distr;

  distr = [];
  for ( i = 0; i < pref.length; ++i ) {
   pi = pref[ i ];
   if ( pi.length !== 1 ) {
     continue;
   }
   if ( hist[ pi[ 0 ] ] === 0 ) {
     return;
   }
   distr[ i ] = pi[ 0 ];
   --hist[ pi[ 0 ] ];
  }

  varPrefHist = { "S": 0, "M": 0, "L": 0, "XL": 0, "XXL": 0, "XXXL": 0};
  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }
    ++varPrefHist[ pi[ 0 ] ];
    ++varPrefHist[ pi[ 1 ] ];
  }

  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }
    print( JSON.stringify( hist ) );
    // Greedy choise. Choose one that in least demand.
    if ( ( varPrefHist[ pi[ 0 ] ] > varPrefHist[ pi[ 1 ] ] || hist[ pi[ 0 ] ] === 0 ) && hist[ pi[ 1 ] ] > 0 ) {
      distr[ i ] = pi[ 1 ];
      --hist[ pi[ 1 ] ];
    } else if ( ( varPrefHist[ pi[ 0 ] ] <= varPrefHist[ pi[ 1 ] ] || hist[ pi[ 1 ] ] === 0 ) && hist[ pi[ 0 ] ] > 0 ) {
      distr[ i ] = pi[ 0 ];
      --hist[ pi[ 0 ] ];
    }  else {
      return;
    }
  }

  return distr;
};

var input = readline().split( " " ).map( b => parseInt( b, 10 ) );
var hist = { "S": input[0], "M": input[1], "L": input[2], "XL": input[3], "XXL": input[4], "XXXL": input[5]};
readline();
var line,
  pref;
pref = [];
while ( line = readline() ) {
  pref.push( line.split( "," ) );
}

var result = calcDistr( hist, pref );
if ( result ) {
  print( "YES" );
  print( result.join( "\n" ) );
} else {
  print( "NO" );
}

// Greedy solution, O(n) runtime and O(n) memory.

var calcDistr = function ( hist, pref ) {
  var varPrefHist,
    i,
    pi,
    distr;

  distr = [];
  for ( i = 0; i < pref.length; ++i ) {
   pi = pref[ i ];
   if ( pi.length !== 1 ) {
     continue;
   }
   if ( hist[ pi[ 0 ] ] === 0 ) {
     return;
   }
   distr[ i ] = pi[ 0 ];
   --hist[ pi[ 0 ] ];
  }

  varPrefHist = { "S": 0, "M": 0, "L": 0, "XL": 0, "XXL": 0, "XXXL": 0};
  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }
    ++varPrefHist[ pi[ 0 ] ];
    ++varPrefHist[ pi[ 1 ] ];
  }

  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }

    // Greedy choise. Choose one that in least demand.
    if ( ( varPrefHist[ pi[ 0 ] ] > varPrefHist[ pi[ 1 ] ] || hist[ pi[ 0 ] ] === 0 ) && hist[ pi[ 1 ] ] > 0 ) {
      distr[ i ] = pi[ 1 ];
      --hist[ pi[ 1 ] ];
    } else if ( ( varPrefHist[ pi[ 0 ] ] <= varPrefHist[ pi[ 1 ] ] || hist[ pi[ 1 ] ] === 0 ) && hist[ pi[ 0 ] ] > 0 ) {
      distr[ i ] = pi[ 0 ];
      --hist[ pi[ 0 ] ];
    }  else {
      return;
    }
  }

  return distr;
};

var input = readline().split( " " ).map( b => parseInt( b, 10 ) );
var hist = { "S": input[0], "M": input[1], "L": input[2], "XL": input[3], "XXL": input[4], "XXXL": input[5]};
readline();
var line,
  pref;
pref = [];
while ( line = readline() ) {
  pref.push( line.split( "," ) );
}

var result = calcDistr( hist, pref );
if ( result ) {
  print( "YES" );
  print( result.join( "\n" ) );
} else {
  print( "NO" );
}

// Greedy solution, O(n) runtime and O(n) memory.

var calcDistr = function ( hist, pref ) {
  var varPrefHist,
    i,
    pi,
    distr;

  distr = [];
  for ( i = 0; i < pref.length; ++i ) {
   pi = pref[ i ];
   if ( pi.length !== 1 ) {
     continue;
   }
   if ( hist[ pi[ 0 ] ] === 0 ) {
     return;
   }
   distr[ i ] = pi[ 0 ];
   --hist[ pi[ 0 ] ];
  }

  varPrefHist = { "S": 0, "M": 0, "L": 0, "XL": 0, "XXL": 0, "XXXL": 0};
  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }
    ++varPrefHist[ pi[ 0 ] ];
    ++varPrefHist[ pi[ 1 ] ];
  }

  for ( i = 0; i < pref.length; ++i ) {
    pi = pref[ i ];
    if ( pi.length !== 2 ) {
      continue;
    }
    // Greedy choise. Choose one that in least demand.
    if ( varPrefHist[ pi[ 0 ] ] >= varPrefHist[ pi[ 1 ] ] && hist[ pi[ 1 ] ] > 0 ) {
      distr[ i ] = pi[ 1 ];
      --hist[ pi[ 1 ] ];
    } else if ( hist[ pi[ 0 ] ] > 0 ) {
      distr[ i ] = pi[ 0 ];
      --hist[ pi[ 0 ] ];
    } else {
      return;
    }
  }

  return distr;
};

var input = readline().split( " " ).map( b => parseInt( b, 10 ) );
var hist = { "S": input[0], "M": input[1], "L": input[2], "XL": input[3], "XXL": input[4], "XXXL": input[5]};
readline();
var line,
  pref;
pref = [];
while ( line = readline() ) {
  pref.push( line.split( "," ) );
}

var result = calcDistr( hist, pref );
if ( result ) {
  print( "YES" );
  print( result.join( "\n" ) );
} else {
  print( "NO" );
}


This is the easy version of this problem. In this version, we do not have queries. Note that we have multiple test cases in this version. You can make hacks only if both versions of the problem are solved.An array $$$b$$$ of length $$$m$$$ is good if for all $$$i$$$ the $$$i$$$-th element is greater than or equal to $$$i$$$. In other words, $$$b$$$ is good if and only if $$$b_i \geq i$$$ for all $$$i$$$ ($$$1 \leq i \leq m$$$).You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. Find the number of pairs of indices $$$(l, r)$$$, where $$$1 \le l \le r \le n$$$, such that the array $$$[a_l, a_{l+1}, \ldots, a_r]$$$ is good.

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

For each test case, print the number of suitable pairs of indices.

NoteIn the first test case, all subarrays of $$$a$$$ are good, so all pairs are suitable.In the second test case, the pairs $$$(1, 1)$$$, $$$(2, 2)$$$, and $$$(3, 3)$$$ are suitable. For example, when $$$(l, r) = (1, 2)$$$, the array $$$b=[1,1]$$$ is not good because $$$b_2 < 2$$$.

// Common Template Starts //
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()
})

const readline = () => inputString[currentLine++]
// Common Template Ends //

// Driver Function Starts //
const main = () => {
    console.clear()
    let t = parseInt(readline())
    while (t--) {
        let n = parseInt(readline())
        let a = readline().split(' ').map(Number)
        console.log(solve(n, a))
    }
}
// Driver Function Ends //

// MAIN LOGIC
const solve = (n, a) => {
    let left = 0
    let right = 0
    let count = 0
    while (left < n) {
        if (right < left) right = left
        while (right < n && a[right] >= right - left + 1) {
            right++
        }
        count += right - left
        left++
    }
    return count
}

const gcd = (a, b) => b == 0 ? a : gcd(b, a % b)

const isOdd = (num) => num & 1
const isEven = (num) => !(num & 1)
const minOfArray = (arr) => Math.min.apply(null, arr)
const maxOfArray = (arr) => Math.max.apply(null, arr)
const uniqueArray = (arr) => [...new Set(arr)]
const sortArray = (arr) => arr.sort((a, b) => a - b)
const sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n);
  const dp = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    var _dp;
    dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
  }
  return dp.reduce((a, b) => a + b, 0);
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8')
.split(/\s+/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();


A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of $$$n$$$ ($$$n \ge 3$$$) positive distinct integers (i.e. different, no duplicates are allowed).Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer $$$x$$$ is called composite if there exists a positive integer $$$y$$$ such that $$$1 < y < x$$$ and $$$x$$$ is divisible by $$$y$$$.If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.

Each test consists of multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 100$$$) — the length of the array. The second line of each test case contains $$$n$$$ distinct integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$1 \leq a_{i} \leq 200$$$) — the elements of the array.

Each test case should have two lines of output. The first line should contain a single integer $$$x$$$: the size of the largest subset with composite sum. The next line should contain $$$x$$$ space separated integers representing the indices of the subset of the initial array.

NoteIn the first test case, the subset $$$\{a_2, a_1\}$$$ has a sum of $$$9$$$, which is a composite number. The only subset of size $$$3$$$ has a prime sum equal to $$$11$$$. Note that you could also have selected the subset $$$\{a_1, a_3\}$$$ with sum $$$8 + 2 = 10$$$, which is composite as it's divisible by $$$2$$$.In the second test case, the sum of all elements equals to $$$21$$$, which is a composite number. Here we simply take the whole array as our subset.

//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 odd = [];
		var even = [];
		var sum = 0;
		for(var i = 0; i < N; i++){
			sum += list[i];
			if(list[i] % 2 == 1){
				odd.push(i + 1);
			}else{
				even.push(i + 1);
			}
		}

		if(isPrime(sum)){
			odd.pop();
		}
		myout(odd.length + even.length);
		myout(myconv(odd.concat(even), 8));
	}
}
function isPrime(val){
	if(val == null || val <= 1 || (val != 2 && val % 2 == 0)){
		return false;
	}else if(val == 2){
		return true;
	}
	var root = Math.floor(Math.sqrt(val));
	for(var i = 3; i <= root; i += 2){
		if(val % i == 0){
			return false;
		}
	}
	return true;
}

//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 odd = [];
		var even = [];
		var sum = 0;
		for(var i = 0; i < N; i++){
			sum += list[i];
			if(list[i] % 2 == 1){
				odd.push(i + 1);
			}else{
				even.push(i + 1);
			}
		}

		if(isPrime(sum)){
			even.pop();
		}
		myout(odd.length + even.length);
		myout(myconv(odd.concat(even), 8));
	}
}
function isPrime(val){
	if(val == null || val <= 1 || (val != 2 && val % 2 == 0)){
		return false;
	}else if(val == 2){
		return true;
	}
	var root = Math.floor(Math.sqrt(val));
	for(var i = 3; i <= root; i += 2){
		if(val % i == 0){
			return false;
		}
	}
	return true;
}


You are given a long decimal number $$$a$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$. You also have a function $$$f$$$ that maps every digit from $$$1$$$ to $$$9$$$ to some (possibly the same) digit from $$$1$$$ to $$$9$$$.You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in $$$a$$$, and replace each digit $$$x$$$ from this segment with $$$f(x)$$$. For example, if $$$a = 1337$$$, $$$f(1) = 1$$$, $$$f(3) = 5$$$, $$$f(7) = 3$$$, and you choose the segment consisting of three rightmost digits, you get $$$1553$$$ as the result.What is the maximum possible number you can obtain applying this operation no more than once?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of digits in $$$a$$$. The second line contains a string of $$$n$$$ characters, denoting the number $$$a$$$. Each character is a decimal digit from $$$1$$$ to $$$9$$$. The third line contains exactly $$$9$$$ integers $$$f(1)$$$, $$$f(2)$$$, ..., $$$f(9)$$$ ($$$1 \le f(i) \le 9$$$).

Print the maximum number you can get after applying the operation described in the statement no more than once.

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var n = read.number();
    var a = read.arrNumber();
    var f = read.arrNumber(' ');

    var res = [];
    var start = false;
    var end = false;
    for(var i = 0; i < n; i++) {
        if((a[i] < f[a[i] -1] && !end) || (a[i] == f[a[i] -1] && start && !end)) {
            res[i] =  f[a[i] -1];
            start = true
        }
        else {
            res[i] = a[i];
            if(start) {
                end = true;
            }
        }
    }

    print(res.join(''));
}())

let n;
let a;
let f;

const run = () => {
  let start;
  let end;
  let el;
  let i;
  for (i = 0; i < n; ++i) {
    el = a[i];
    if (el < f[el]) {
      start = i;
      for (; i < n; ++i) {
        el = a[i];
        end = i;
        if (el > f[el]) {
          end = i - 1;
          break;
        }
      }
      break;
    }
  }
  if (start === undefined) {
    console.log(a.join(''))
    return;
  }
  console.log(a.map((e, j) => ((j >= start && (end === undefined || j <= end)) ? f[e] : e)).join(''))
}

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

rl.on('line', (data) => {
  if (n === undefined) {
    n = +(data.toString());
    return;
  }
  if (a === undefined) {
    a = data.toString().trim().split('').map(Number);
    return;
  }
  f = [null, ...data.toString().trim().split(/\s+/g).filter(Boolean).map(Number)];
  run();
  rl.close();
})

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var n = read.number();
    var a = read.arrNumber();
    var f = read.arrNumber(' ');

    var res = [];
    for(var i =0 ;i < n; i++) {
        res[i] = a[i] > f[a[i] -1] ? a[i] : f[a[i] -1];
    }

    print(res.join(''));
}());

let n;
let a;
let f;
const promise = new Promise(resolve => {
  process.stdin.on('data', (data) => {
    if (n === undefined) {
      n = +(data.toString());
      return;
    }
    if (a === undefined) {
      a = data.toString().trim().split('').map(Number);
      return;
    }
    f = [null, ...data.toString().trim().split(/\s+/g).filter(Boolean).map(Number)];
    resolve();
  })
})

promise.then(() => {
  let start;
  let end;
  let el;
  let k;
  let i;
  for (i = 0; i < n; ++i) {
    el = a[i];
    if (el < f[el]) {
      start = i;
      for (k = i + 1; k < n; ++k) {
        el = a[k];
        if (el > f[el]) {
          end = k;
          break;
        }
      }
      break;
    }
  }
  if (start === undefined) {
    console.log(a.join(''))
    return;
  }
  console.log(a.map((e, j) => {
    if (j >= start && (end === undefined || j <= end)) {
      return f[e];
    }
    return e;
  }).join(''))
})

let n;
let a;
let f;
const promise = new Promise(resolve => {
  process.stdin.on('data', (data) => {
    if (n === undefined) {
      n = +(data.toString());
      return;
    }
    if (a === undefined) {
      a = data.toString().split('');
      return;
    }
    f = ['x', ...data.toString().split(/\s+/g).filter(Boolean).map(Number)];
    resolve();
  })
})

promise.then(() => {
  const b = [];
  for (let k = 1; k < 10; ++k) {
    b[k] = k < f[k];
  }
  let i = 0;
  let start;
  let end;
  for (; i < n; ++i) {
    if (b[a[i]]) {
      if (start === undefined) {
        start = i;
      } else if (end === undefined) {
        end = i;
        break;
      }
    }
  }
  console.log(a.map((e, j) => {
    if (j >= start && j <= end) {
      return f[e];
    }
    return e;
  }).join(''))
})

let n;
let a;
let f;
const promise = new Promise(resolve => {
  process.stdin.on('data', (data) => {
    if (n === undefined) {
      n = +(data.toString());
      return;
    }
    if (a === undefined) {
      a = data.toString().trim().split('').map(Number);
      return;
    }
    f = [null, ...data.toString().trim().split(/\s+/g).filter(Boolean).map(Number)];
    resolve();
  })
})

promise.then(() => {
  let start;
  let end;
  let el;
  let k;
  let i;
  for (i = 0; i < n; ++i) {
    el = a[i];
    if (el < f[el]) {
      start = i;
      for (k = i + 1; k < n; ++k) {
        el = a[k];
        if (el >= f[el]) {
          end = k - 1;
          break;
        }
      }
      break;
    }
  }
  if (start === undefined) {
    console.log(a.join(''))
    return;
  }
  console.log(a.map((e, j) => {
    if (j >= start && (end === undefined || j <= end)) {
      return f[e];
    }
    return e;
  }).join(''))
})


One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?

The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).

If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.

//

var line = readline();

var ray = readline().split(' ');
var n = parseInt(line);
var bRay = [];

for(var i = 0 ; i < n ; i++) {
	bRay.push(parseInt(ray[i]));
}

print(foo(n,bRay));

//console.log(foo(2,[1,2]));

//checker(3,[1,3,2],0);
function foo(n,ray) {
	var count = 0;
	//console.log(checker(n,bRay,1));

	for(var i = 0 ; i < n-1;i++) {
		if (ray[i] > ray[i+1]) {

			for(var j = 1 ; j < n ; j++) {
				//.log((j+i)%n,i);
				if ( ray[(j+i) % n]  > ray[(j+i+1) %n]) {
					return -1;
				}

			}
			return n-(i+1);

		}

	}

	return 0;
}

/*
function checker(n,ray,p) {
//	var s = "";
//	var d = "";
	for(var i = 0 ; i < n-1 ; i++) {

		if ( ray[(i+p) %n] > ray[(i+1+p) %n]) {
			return false;
		}

	}

	return true;
}*/

function ProblemSolver() {
    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;
    this.CLEAR_ARRAY_PER_CASE = false;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , prev ;
        res = ( 1 << 20 ) ;
        prev = -1 ;
        fl = 1 ;
        for( i = 0 ; i < this.n ; i++ ) {
        	if( this.arr[ i ] >= prev ) {
        		prev = this.arr[ i ] ;
        	}
        	else {
        		fl = 0 ;
        		prev = -1 ;
        		for( j = i ; j < this.n ; j++ ) {
        			if( this.arr[ j ] >= prev ) {
		        		prev = this.arr[ j ] ;
		        	}
		        	else {
		        		break ;
		        	}
        		}
        		if( j == this.n && this.arr[ this.n - 1 ] <= this.arr[ 0 ] ) {
        			res = this.n - i ;
        		}
        		break ;
        	}
        }
        if( fl == 1 ) {
        	res = 0 ;
        }
        if( res == ( 1 << 20 ) ) {
        	res = -1 ;
        }
        print( res );
    };

    this.init = function() {
        this.lim1 = 100010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.n = irObj.nextInt();
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr[ i ] = irObj.nextInt();
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

    this.clearArraysPerCase = function() {
        var i;
        this.arr = new Array();
        this.adj_list = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 );
            this.adj_list.push( new Array() );
        }
    };

    this.clearPerCase = function() {
        this.cn = 0;
        this.cc++;
        if( this.CLEAR_ARRAY_PER_CASE == true ) {
            this.clearArraysPerCase() ;
        }
    };

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adj_list = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( "" );
            this.vis.push( 0 );
            this.arr.push( 0 );
            this.brr.push( 0 );
            this.adj_list.push( new Array() );
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() );
            this.done.push( new Array() );
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 );
                this.done[ i ].push( 0 );
            }
        }
    };

    this.init();
}

function InputReader() {
    var self = this ;
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;
    this.callBackFunction = null ;
    this.parentContext = null ;

    this.readAllLines = function() {
        var singleLine;
        while( true ) {
            try {
                singleLine = readline();
                if( singleLine == null ) {
                    break;
                }
            }
            catch( ex ) {
                break;
            }
            this.allLines.push( singleLine );
        }
    };

    this.readAllLinesFromRhino = function() {
        var brObj , line ;
        importPackage( java.io ) ;
        importPackage( java.lang ) ;
        brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;
        this.allLines = [] ;
        while( true ) {
            line = brObj.readLine() ;
            if( line == null ) {
                break;
            }
            this.allLines.push( line ) ;
        }
    };

    this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {
        self.chunkData += chunk ;
    };

    this.readEndFromNodeJsJudgeServer = function() {
        self.parseRawData( self.chunkData ) ;
        self.parentContext.runCases() ;
    };

    this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {
        this.parentContext = parentContext ;
        process.stdin.resume() ;
        process.stdin.setEncoding( 'utf8' ) ;
        this.chunkData = '' ;
        process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;
        process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        this.allLines = [] ;
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString );
                currentString = "";
            }
            else {
                currentString += data[ i ];
            }
        }
        if( currentString != "" ) {
            this.allLines.push( currentString );
        }
    };

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx;
        if( flag == 0 ) {
            if( this.currrentCharacterIndex != 0 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            res = "";
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
            }
            this.currrentLineNumber++;
            this.currrentCharacterIndex = 0;
            return res;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( "No more tokens available!" );
            }
            startIdx = -1;
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {
                    startIdx = i;
                    break;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
                continue;
            }
            res = "";
            endIdx = len - 1 ;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {
                    res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;
                }
                else {
                    res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );
                }
            }
            this.currrentCharacterIndex = endIdx;
            if( endIdx == len - 1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            return res;
        }
    };

    this.nextInt = function() {
        return parseInt( this.next( 1 ) );
    };

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) );
    };

    this.nextString = function() {
        return this.next( 1 );
    };

    this.nextLine = function() {
        return this.next( 0 );
    };
}

function FileOutputHandler() {
    this.resultantStringArray = new Array();

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString );
    };

    this.clearPercase = function() {
        this.resultantStringArray = new Array();
    };

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath;
        res = "";
        sz = this.resultantStringArray.length;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += "\n";
            }
            res += this.resultantStringArray[ i ];
        }
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

function CodeExecutioner() {
    this.irObj = new InputReader();
    this.psObj = new ProblemSolver();
    this.fohObj = new FileOutputHandler();

    this.runCases = function() {
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt();
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase();
                this.psObj.getInput( this.irObj );
                this.psObj.solveCase();
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase();
                hasMoreTestCases = this.psObj.getInput( this.irObj );
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase();
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );
        }
    };

    this.detectEnvironmentType = function() {
        var environmentType = null ;
        try {
            if( importPackage != null ) {
                environmentType = 'rhino' ;
            }
        }
        catch( ex1 ) {
            try {
                //for nodejs local server check
                if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {
                    environmentType = 'local-node-js' ;
                }
            }
            catch( ex2 ) {
                try {
                    if( readline == null || typeof( readline ) != 'function' ) {
                        environmentType = 'server-node-js' ;
                    }
                    else {
                        try {
                            if( Map != null ) {
                                environmentType = 'spider-monkey' ;
                            }
                            else {
                                environmentType = 'javascript-v8' ;
                            }
                        }
                        catch( ex3 ) {
                            environmentType = 'javascript-v8' ;
                        }
                    }
                }
                catch( ex3 ) {
                    environmentType = 'server-node-js' ;
                }
            }
        }
        return environmentType ;
    };

    this.configureStreamsAndReadInput = function() {
        var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;
        isNodeJsJudgeServer = false ;
        environmentType = this.detectEnvironmentType() ;
        if( environmentType == 'local-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments );
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );
            this.runCases() ;
        }
        else if( environmentType == 'server-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;
        }
        else if( environmentType == 'javascript-v8' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
        else if( environmentType == 'rhino' ) {
            this.irObj.readAllLinesFromRhino();
            this.runCases() ;
        }
        else if( environmentType == 'spider-monkey' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
    };

    this.configureStreamsAndReadInput();
}

new CodeExecutioner();

var n = +readline();
var s = readline().split(' ').map(Number);
var ind = -1;
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		ind = i+1;
		s = s.slice(ind).concat(s.slice(0, ind));
		break;
	}
}
if (ind == -1) print(0);
else {
	for (var i=0; i<n-1; i++) {
		if (s[i]>s[i+1]) {
		print(-1);
		ind = -1;
		break;
		}
	}
	if (ind != -1) print(n-ind);
}

var n=parseInt(readline());
var ar=readline().split(" ");
for(var i=0;i<n;i++){ar[i]=parseInt(ar[i]);}

var res=0;

if(ar[n-1]>ar[0])
{
   for(var i=0;i<n-1;i++){
           if(ar[i]>ar[i+1]){res=-1;break;}
                        }
}

else{res++;
for(var i=n-1;i>0;i--){

               if(ar[i]>=ar[i-1]){res++;}
else{
for(var y=0;y<i-1;y++){
         if(ar[y]>ar[y+1]){res=-1;break;}
}break;

}
}if(res===n){res=0;}
}print(res);

var l = readline()|0,
    arr = readline().split(' ').map(Number),
    inf = 0,
    steps = 0;

    if (arr[l-1]>arr[0]) {
        inf +=1;
    }
for (var i=0; i<l-1; i++) {
    if (arr[i] > arr[i+1]) {
        inf +=1;
        steps = l-1 - i;
    }
}
if (inf == 0) {
    print('0');
} else if (inf == 1){
    print(steps);
} else {
    print('-1');
}

;(function () {

    print(function () {
        var n = +readline(),
            a = readline().split(' ').map(Number),
            d = 0, r = null;

        if (n === 2) {
            return a[0] <= a[1] ? 0 : 1;
        }

        a = a.concat([a[0]]);

        a.forEach(function (e, i, a) {
            if (i === 0) return;
            if (e < a[i - 1]) {
                d++;
                r = i;
            }
        });

        if (d === 0) return 0;
        if (d > 1) return -1;
        return n - r;
    }.call(this));

}.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 n = parseInt(readline()),
		values = tokenizeIntegers(readline());
	for (var seek = 1; seek < n; ++seek) {
		if (values[seek-1] > values[seek]) {
			break;
		}
	}
	if (seek == n) {
		return 0;
	}
	var end = seek-1;
	for (var i = end+2; i < n; ++i) {
		if (values[i-1] > values[i]) {
			return -1;
		}
	}
	if (values[n-1] > values[0]) {
		return -1;
	}
	return n-end-1;
}

print(main());

//

var line = readline();

var ray = readline().split(' ');
var n = parseInt(line);
var bRay = [];

for(var i = 0 ; i < n ; i++) {
	bRay.push(parseInt(ray[i]));
}

print(foo(n,bRay));

//console.log(foo(4,[3,4,1,2]));

//checker(3,[1,3,2],0);
function foo(n,ray) {
	var count = 0;
	//console.log(checker(n,bRay,1));

	for(var i = 0 ; i < n-1;i++) {
		if (ray[i] > ray[i+1]) {

			for(var j = 1 ; j < n ; j++) {
				//.log((j+i)%n,i);
				if ( ray[(j+i) % n]  > ray[(j+i+1) %n]) {
					return -1;
				}

			}
			return i+1;

		}

	}

	return 0;
}

/*
function checker(n,ray,p) {
//	var s = "";
//	var d = "";
	for(var i = 0 ; i < n-1 ; i++) {

		if ( ray[(i+p) %n] > ray[(i+1+p) %n]) {
			return false;
		}

	}

	return true;
}*/

//

var line = readline();

var ray = readline().split(' ');
var n = parseInt(line);
var bRay = [];

for(var i = 0 ; i < n ; i++) {
	bRay.push(parseInt(ray[i]));
}

print(foo(n,bRay));

//console.log(foo(3,[1,3,2]));
function foo(n,bRay) {
	var count = 0;
	//console.log(checker(n,bRay,1));

		for(var i = 0 ; i < n ; i++) {

			if ( checker(n,bRay,i)) {
				//console.log(checker(n,bRay,i),n,bRay,i);
				return count;
			}
			count++;

		}

	return -1;

}

function checker(n,ray,p) {
	//console.log(n,ray,p);
	for(var i = 0 ; i < n ; i++) {

		var j = (i+p) %n ;
		//console.log(ray[j]);
		if ( ray[j] > ray[(j+1)%n]) {
			return false;
		}

	}
	//console.log("e");
	return true ;

}

function ProblemSolver() {
    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;
    this.CLEAR_ARRAY_PER_CASE = false;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , prev ;
        res = ( 1 << 20 ) ;
        prev = -1 ;
        fl = 1 ;
        for( i = 0 ; i < this.n ; i++ ) {
        	if( this.arr[ i ] >= prev ) {
        		prev = this.arr[ i ] ;
        	}
        	else {
        		fl = 0 ;
        		prev = -1 ;
        		for( j = i ; j < this.n ; j++ ) {
        			if( this.arr[ i ] >= prev ) {
		        		prev = this.arr[ i ] ;
		        	}
		        	else {
		        		break ;
		        	}
        		}
        		if( j == this.n && this.arr[ this.n - 1 ] <= this.arr[ 0 ] ) {
        			res = this.n - i ;
        		}
        		break ;
        	}
        }
        if( fl == 1 ) {
        	res = 0 ;
        }
        if( res == ( 1 << 20 ) ) {
        	res = -1 ;
        }
        print( res );
    };

    this.init = function() {
        this.lim1 = 100010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.n = irObj.nextInt();
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr[ i ] = irObj.nextInt();
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

    this.clearArraysPerCase = function() {
        var i;
        this.arr = new Array();
        this.adj_list = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 );
            this.adj_list.push( new Array() );
        }
    };

    this.clearPerCase = function() {
        this.cn = 0;
        this.cc++;
        if( this.CLEAR_ARRAY_PER_CASE == true ) {
            this.clearArraysPerCase() ;
        }
    };

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adj_list = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( "" );
            this.vis.push( 0 );
            this.arr.push( 0 );
            this.brr.push( 0 );
            this.adj_list.push( new Array() );
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() );
            this.done.push( new Array() );
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 );
                this.done[ i ].push( 0 );
            }
        }
    };

    this.init();
}

function InputReader() {
    var self = this ;
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;
    this.callBackFunction = null ;
    this.parentContext = null ;

    this.readAllLines = function() {
        var singleLine;
        while( true ) {
            try {
                singleLine = readline();
                if( singleLine == null ) {
                    break;
                }
            }
            catch( ex ) {
                break;
            }
            this.allLines.push( singleLine );
        }
    };

    this.readAllLinesFromRhino = function() {
        var brObj , line ;
        importPackage( java.io ) ;
        importPackage( java.lang ) ;
        brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;
        this.allLines = [] ;
        while( true ) {
            line = brObj.readLine() ;
            if( line == null ) {
                break;
            }
            this.allLines.push( line ) ;
        }
    };

    this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {
        self.chunkData += chunk ;
    };

    this.readEndFromNodeJsJudgeServer = function() {
        self.parseRawData( self.chunkData ) ;
        self.parentContext.runCases() ;
    };

    this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {
        this.parentContext = parentContext ;
        process.stdin.resume() ;
        process.stdin.setEncoding( 'utf8' ) ;
        this.chunkData = '' ;
        process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;
        process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        this.allLines = [] ;
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString );
                currentString = "";
            }
            else {
                currentString += data[ i ];
            }
        }
        if( currentString != "" ) {
            this.allLines.push( currentString );
        }
    };

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx;
        if( flag == 0 ) {
            if( this.currrentCharacterIndex != 0 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            res = "";
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
            }
            this.currrentLineNumber++;
            this.currrentCharacterIndex = 0;
            return res;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( "No more tokens available!" );
            }
            startIdx = -1;
            len = this.allLines[ this.currrentLineNumber ].length;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {
                    startIdx = i;
                    break;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
                continue;
            }
            res = "";
            endIdx = len - 1 ;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {
                    res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;
                }
                else {
                    res += '' + this.allLines[ this.currrentLineNumber ].charAt( i );
                }
            }
            this.currrentCharacterIndex = endIdx;
            if( endIdx == len - 1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            return res;
        }
    };

    this.nextInt = function() {
        return parseInt( this.next( 1 ) );
    };

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) );
    };

    this.nextString = function() {
        return this.next( 1 );
    };

    this.nextLine = function() {
        return this.next( 0 );
    };
}

function FileOutputHandler() {
    this.resultantStringArray = new Array();

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString );
    };

    this.clearPercase = function() {
        this.resultantStringArray = new Array();
    };

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath;
        res = "";
        sz = this.resultantStringArray.length;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += "\n";
            }
            res += this.resultantStringArray[ i ];
        }
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

function CodeExecutioner() {
    this.irObj = new InputReader();
    this.psObj = new ProblemSolver();
    this.fohObj = new FileOutputHandler();

    this.runCases = function() {
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt();
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase();
                this.psObj.getInput( this.irObj );
                this.psObj.solveCase();
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase();
                hasMoreTestCases = this.psObj.getInput( this.irObj );
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase();
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME );
        }
    };

    this.detectEnvironmentType = function() {
        var environmentType = null ;
        try {
            if( importPackage != null ) {
                environmentType = 'rhino' ;
            }
        }
        catch( ex1 ) {
            try {
                //for nodejs local server check
                if( __dirname != null && readline != null && typeof( readline ) != 'function' ) {
                    environmentType = 'local-node-js' ;
                }
            }
            catch( ex2 ) {
                try {
                    if( readline == null || typeof( readline ) != 'function' ) {
                        environmentType = 'server-node-js' ;
                    }
                    else {
                        try {
                            if( Map != null ) {
                                environmentType = 'spider-monkey' ;
                            }
                            else {
                                environmentType = 'javascript-v8' ;
                            }
                        }
                        catch( ex3 ) {
                            environmentType = 'javascript-v8' ;
                        }
                    }
                }
                catch( ex3 ) {
                    environmentType = 'server-node-js' ;
                }
            }
        }
        return environmentType ;
    };

    this.configureStreamsAndReadInput = function() {
        var testCases , i , hasMoreTestCases , isLocal , localContext , isNodeJsJudgeServer , environmentType ;
        isNodeJsJudgeServer = false ;
        environmentType = this.detectEnvironmentType() ;
        if( environmentType == 'local-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments );
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME );
            this.runCases() ;
        }
        else if( environmentType == 'server-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log;
                }
            }
            catch( ex ) {
                print = console.log;
            }
            this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;
        }
        else if( environmentType == 'javascript-v8' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
        else if( environmentType == 'rhino' ) {
            this.irObj.readAllLinesFromRhino();
            this.runCases() ;
        }
        else if( environmentType == 'spider-monkey' ) {
            this.irObj.readAllLines();
            this.runCases() ;
        }
    };

    this.configureStreamsAndReadInput();
}

new CodeExecutioner();

var n = +readline();
var s = readline().split(' ').map(Number);
var min = 1000000;
var ind = 0;
var count = 0;
for (var i=0; i<n; i++) {
	if (s[i]<=min) {
		min = s[i];
		ind = i;
	}
}
s = s.slice(ind).concat(s.slice(0, ind));
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		print(-1);
		min = 10000000;
		break;
	}
	if (s[i]==s[i+1]) {
		count++;
	}
}
if (min != 10000000) {
	if (ind == 0 || count == n-1) print(0);
	else print(n-ind);
}

var n = +readline();
var s = readline().split(' ').map(Number);
var min = 1000000;
var ind = 0;
for (var i=0; i<n; i++) {
	if (s[i]<=min) {
		min = s[i];
		ind = i;
	}
}
s = s.slice(ind).concat(s.slice(0, ind));
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		print(-1);
		min = 10000000;
		break;
	}
}
if (min != 10000000) {
	if (ind == 0) print(0);
	else print(n-ind);
}

var n = +readline();
var s = readline().split(' ').map(Number);
var min = Math.min.apply(null, s);
var ind = s.indexOf(min);
var count = 0;
s = s.slice(ind).concat(s.slice(0, ind));
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		print(-1);
		min = 10000000;
		break;
	}
	if (s[i]==s[i+1]) {
		count++;
	}
}
if (min != 10000000) {
	if (ind == 0 || count == n-1) print(0);
	else print(n-ind);
}

var n = +readline();
var s = readline().split(' ').map(Number);
var min = 1000000;
var ind = 0;
for (var i=0; i<n; i++) {
	if (s[i]<=min) {
		min = s[i];
		ind = i;
	}
}
s = s.slice(ind).join('') + s.slice(0, ind).join('');
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		print(-1);
		min = 10000000;
		break;
	}
}
if (min != 10000000) {
	if (ind == 0) print(0);
	else print(n-ind);
}

var n = +readline();
var s = readline().split(' ').map(Number);
var min = 1000000;
var ind = 0;
for (var i=0; i<n; i++) {
	if (s[i]<=min) {
		min = s[i];
		ind = i;
	}
}
s = s.slice(ind).concat(s.slice(0, ind));
print(s);
for (var i=0; i<n-1; i++) {
    if (s[i]>s[i+1]) {
		print(-1);
		min = 10000000;
		break;
	}
}
if (min != 10000000) {
	if (ind == 0) print(0);
	else print(n-ind);
}

var n=parseInt(readline());
var ar=readline().split(" ");

var res=0;

if(parseInt(ar[n-1])>parseInt(ar[0]))
{
   for(var i=0;i<n-1;i++){
           if(parseInt(ar[i])>parseInt(ar[i+1])){res=-1;break;}
                        }
}

else{
res++;
for(var i=n-1;i>0;i--){

               if(parseInt(ar[i-1])<=parseInt(ar[i])){res++;}
else{
for(var y=i-1;y>0;y--){
         if(parseInt(ar[y])<parseInt(ar[y-1])){res=-1;break;}
}
}
break;
}
}print(res);

var n=parseInt(readline());
var ar=readline().split(" ");
var res=0;
if(parseInt(ar[n-1])>parseInt(ar[0])){
for(var i=0;i<n-1;i++){
if(parseInt(ar[i])>parseInt(ar[i+1])){res=-1;break;}
}
}
else{
res++;
for(var i=n-1;i>0;i--){

if(parseInt(ar[i-1])<parseInt(ar[i])){res++;}
else{
for(var y=i-1;y>0;y--){
if(parseInt(ar[y])<parseInt(ar[y-1])){res=-1;break;}
}
}
break;
}
}print(res);

var n=parseInt(readline());
var ar=readline().split(" ");
for(var i=0;i<n;i++){ar[i]=parseInt(ar[i]);}

var res=0;

if(ar[n-1]>ar[0])
{
   for(var i=0;i<n-1;i++){
           if(ar[i]>ar[i+1]){res=-1;break;}
                        }
}

else{res++;
for(var i=n-1;i>0;i--){

               if(ar[i]>ar[i-1]){res++;}
else{
for(var y=0;y<i-1;y++){
         if(ar[y]>ar[y+1]){res=-1;break;}
}break;

}
}
}print(res);

var l = readline()|0,
    arr = readline().split(' ').map(Number),
    chkr = false,
    chk = false;

while (chkr == false) {
    var res = 0;
    for (var i = 0; i < l-1; i++) {
        if (arr[i] > arr[i+1]) {
            arr.unshift(arr.pop(arr[l-1]));
            chkr = false;
            break;
        }
        chkr = true;
        chk = true;
        res += 1;
    }
    if (res >= l-1) {
        chkr = true;
        chk = false;
    }
}
if (chk == true) {
   print(res);
}
else {
   print ("-1");
}

;(function () {

    print(function () {
        var n = +readline(),
            a = readline().split(' ').map(Number),
            d = 0, r = null;

        if (n === 2) {
            return a[0] <= a[1] ? 0 : 1;
        }

        a.forEach(function (e, i, a) {
            if (i === 0) return;
            if (e < a[i - 1]) {
                d++;
                r = i;
            }
        });

        if (d === 0) return 0;
        if (d > 1) return -1;
        return n - r;
    }.call(this));

}.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 n = parseInt(readline()),
		values = tokenizeIntegers(readline());
	for (var seek = 1; seek < n; ++seek) {
		if (values[seek-1] > values[seek]) {
			break;
		}
	}
	if (seek == n) {
		return 0;
	}
	var end = seek-1;
	for (var i = end+2; i < n; ++i) {
		if (values[i-1] > values[i]) {
			return -1;
		}
	}
	if (values[n-1] > values[0]) {
		return -1;
	}
	return Math.min(end+1, n-end-1);
}

print(main());

//

var line = readline();

var ray = readline().split(' ');
var n = parseInt(line);
var bRay = [];

for(var i = 0 ; i < n ; i++) {
	bRay.push(parseInt(ray[i]));
}

print(foo(n,bRay));

//console.log(foo(2,[2,1]));
function foo(n,bRay) {
	var count = 0;
	//console.log(checker(n,bRay,1));
	if ( !checker(n,bRay,0) ) {

		for(var i = 1 ; i < n ; i++) {

			count++;
			if ( checker(n,bRay,i)) {
				return count;
			}

		}
	}

	else {
		return 0;
	}

	return -1;

}

function checker(n,ray,p) {
	for(var i = 0 ; i < n-1 ; i++) {
		var j = (i+p) %n ;
		if ( ray[j] > ray[j+1]) {
			return false;
		}

	}

	return true ;

}


This problem is a complicated version of D1, but it has significant differences, so read the whole statement.Polycarp has an array of $$$n$$$ ($$$n$$$ is even) integers $$$a_1, a_2, \dots, a_n$$$. Polycarp conceived of a positive integer $$$k$$$. After that, Polycarp began performing the following operations on the array: take an index $$$i$$$ ($$$1 \le i \le n$$$) and reduce the number $$$a_i$$$ by $$$k$$$.After Polycarp performed some (possibly zero) number of such operations, it turned out that at least half of the numbers in the array became the same. Find the maximum $$$k$$$ at which such a situation is possible, or print $$$-1$$$ if such a number can be arbitrarily large.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even integer $$$n$$$ ($$$4 \le n \le 40$$$) ($$$n$$$ is even). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$). It is guaranteed that the sum of all $$$n$$$ specified in the given test cases does not exceed $$$100$$$.

For each test case output on a separate line an integer $$$k$$$ ($$$k \ge 1$$$) — the maximum possible number that Polycarp used in operations on the array, or $$$-1$$$, if such a number can be arbitrarily large.

const readline = require('readline')

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

function solve(n, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        map[x] = (map[x] || 0) + 1
        if (map[x] >= n / 2) return -1
    }

    let ans = -1
    for (let i = 0; i < arr.length; i++) {
        // set arr[i] as target
        const ds = []
        for (let j = 0; j < arr.length; j++) {
            ds[j] = arr[j] - arr[i]
        }
        // try each possible gcd
        const gs = {}
        for (let j = 0; j < arr.length; j++) {
            if (ds[j] <= 0) continue
            gs[ds[j]] = 1

            for (let k = 0; k < arr.length; k++) {
                if (k === i || k === j || ds[k] <= 0) continue

                const g = gcd(ds[j], ds[k])
                gs[g] = 1
            }
        }
        for (let g in gs) {
            g = +g
            if (g > ans) {
                let count = map[arr[i]] // already
                for (let x = 0; x < arr.length; x++) {
                    if (ds[x] <= 0 || (ds[x] % g)) continue
                    count++
                }
            // console.log(`target=${arr[i]} g=${g} count=${count}`)
                if (count >= n / 2) ans = g
            }
        }
    }
    return ans
}
function gcd(a, b) {
    if (a === 0) return b
    if (b === 0) return a

    while (a) {
        const r = b % a
        b = a
        a = r
    }
    return b
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function gcd(a, b) {
    if (b == 0)
        return a;
    return gcd(b, a % b);
}

function abs(a) {
    return Math.max(a, -a);
}
function main() {
    let t = Number(readline())
    for (let j = 1; j <= t; j++) {
        let is = 0
        const map = new Map()
        let n = Number(readline())
        let a = readline().split(' ').map(Number)
        for (let i = 0; i < n; i++) {
            if (map.has(a[i]))
                map.set(a[i], map.get(a[i]) + 1)
            else
                map.set(a[i], 1)
            if (map.get(a[i]) >= n / 2)
                is = 1
        }
        if (is) {
            console.log(-1)
            continue
        }
        let ans = 0
        for (let i = 0; i < n; i++) {
            for (let j = i + 1; j < n; j++) {
                let big = abs(a[i] - a[j])
                for (let cand = 1; cand * cand <= big; cand++) {
                    let count = 0
                    if (big % cand) continue;
                    for (let k = 0; k < n; k++) {
                        if (abs(a[i] - a[k]) % cand) continue;
                        count++
                    }
                    if (count >= n / 2)
                        ans = Math.max(cand, ans)
                    count = 0
                    let cand1=big/cand
                    if (big % cand1) continue;
                    for (let k = 0; k < n; k++) {
                        if (abs(a[i] - a[k]) % cand1) continue;
                        count++
                    }
                    if (count >= n / 2)
                        ans = Math.max(cand1, ans)
                }
            }
        }
        console.log(ans)
    }
}

'use strict';
process.stdin.resume();
process.stdin.setEncoding('ascii');
let input = '';
process.stdin.on('data', (data) => {
    input += data;
});
process.stdin.on('end', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
class Scanner {
    constructor(input) {
        this.words = [];
        this.pos = 0;
        input.split('\n').forEach((line) => {
            this.words.push.apply(this.words, line.split(' ').filter(s => s != ''));
        });
    }
    nextInt() {
        return Math.floor(Number(this.words[this.pos++]));
    }
    nextBigInt() {
        return BigInt(this.nextInt());
    }
    nextStr() {
        return this.words[this.pos++];
    }
    eof() {
        return this.pos >= this.words.length;
    }
}
function af(l) {
    return Array.from({ length: l });
}
const INF = Number.MAX_SAFE_INTEGER;
const INIT = -1;
let n;
let a;
function same() {
    let cnt = new Map();
    for (let i = 0; i < n; i++) {
        cnt.set(a[i], (cnt.get(a[i]) || 0) + 1);
    }
    for (let [k, v] of cnt) {
        if (v * 2 >= n) {
            return true;
        }
    }
    return false;
}
function main() {
    const sc = new Scanner(input);
    let tc = sc.nextInt();
    while (tc-- > 0) {
        n = sc.nextInt();
        a = af(n);
        for (let i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        if (same()) {
            process.stdout.write(`-1\n`);
            continue;
        }
        let divs = [];
        for (let i = 0; i < n; i++) {
            for (let j = i + 1; j < n; j++) {
                let diff = Math.abs(a[i] - a[j]);
                for (let k = 1; k * k <= diff; k++) {
                    if ((diff % k) == 0) {
                        divs.push(diff / k);
                        divs.push(k);
                    }
                }
            }
        }
        divs = Array.from(new Set(divs));
        let ans = 0;
        for (let div of divs) {
            for (let i = 0; i < n; i++) {
                let cnt = 0;
                for (let j = 0; j < n; j++) {
                    let diff = Math.abs(a[i] - a[j]);
                    if ((diff % div) == 0) {
                        cnt++;
                    }
                }
                if (cnt * 2 >= n) {
                    ans = Math.max(ans, div);
                }
            }
        }
        process.stdout.write(`${ans}\n`);
    }
}

const readline = require('readline')

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

function solve(n, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        map[x] = (map[x] || 0) + 1
        if (map[x] >= n / 2) return -1
    }

    let ans = -1
    for (let i = 0; i < arr.length; i++) {
        // set arr[i] as target
        const ds = []
        for (let j = 0; j < arr.length; j++) {
            ds[j] = arr[j] - arr[i]
        }
        // try each possible gcd
        const gs = {}
        for (let j = 0; j < arr.length; j++) {
            for (let k = 0; k < arr.length; k++) {
                if (k === i || k === j || ds[j] <= 0) continue

                const g = gcd(ds[j], ds[k])
                gs[g] = 1
            }
        }
        for (let g in gs) {
            g = +g
            if (g > ans) {
                let count = map[arr[i]] // already
                for (let x = 0; x < arr.length; x++) {
                    if (ds[x] <= 0 || (ds[x] % g)) continue
                    count++
                }
            // console.log(`target=${arr[i]} g=${g} count=${count}`)
                if (count >= n / 2) ans = g
            }
        }
    }
    return ans
}
function gcd(a, b) {
    if (a === 0) return b
    if (b === 0) return a

    while (a) {
        const r = b % a
        b = a
        a = r
    }
    return b
}