You are given a matrix consisting of digits zero and one, its size is n × m. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations?Let's assume that the rows of matrix a are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. A matrix cell on the intersection of the i-th row and the j-th column can be represented as (i, j). Formally, a submatrix of matrix a is a group of four integers d, u, l, r (1 ≤ d ≤ u ≤ n; 1 ≤ l ≤ r ≤ m). We will assume that the submatrix contains cells (i, j) (d ≤ i ≤ u; l ≤ j ≤ r). The area of the submatrix is the number of cells it contains.

The first line contains two integers n and m (1 ≤ n, m ≤ 5000). Next n lines contain m characters each — matrix a. Matrix a only contains characters: "0" and "1". Note that the elements of the matrix follow without any spaces in the lines.

Print a single integer — the area of the maximum obtained submatrix. If we cannot obtain a matrix of numbers one, print 0.

// Generated by CoffeeScript 1.4.0
(function() {
  var a, i, l, m, n, readints, res, x, z, z0, z1, zn, _i, _j, _k, _l, _len, _len1, _ref, _ref1, _results;

  readints = function() {
    var x, _i, _len, _ref, _results;
    _ref = readline().split(' ');
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      x = _ref[_i];
      _results.push(x | 0);
    }
    return _results;
  };

  _ref = readints(), n = _ref[0], m = _ref[1];

  a = (function() {
    var _i, _results;
    _results = [];
    for (_i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--) {
      _results.push(readline().split(''));
    }
    return _results;
  })();

  l = (function() {
    var _i, _results;
    _results = [];
    for (_i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--) {
      _results.push(0);
    }
    return _results;
  })();

  z = (function() {
    _results = [];
    for (var _i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--){ _results.push(_i); }
    return _results;
  }).apply(this);

  res = 0;

  for (i = _j = _ref1 = m - 1; _ref1 <= 0 ? _j <= 0 : _j >= 0; i = _ref1 <= 0 ? ++_j : --_j) {
    z0 = [];
    z1 = [];
    for (_k = 0, _len = z.length; _k < _len; _k++) {
      x = z[_k];
      if (a[x][i] === '0') {
        z0.push(x);
        l[x] = 0;
      } else {
        z1.push(x);
        l[x]++;
      }
    }
    zn = z1.length;
    for (_l = 0, _len1 = z1.length; _l < _len1; _l++) {
      x = z1[_l];
      res = Math.max(res, l[x] * zn);
      zn--;
    }
    z = z0.concat(z1);
  }

  print(res);

}).call(this);

// Generated by CoffeeScript 1.4.0
(function() {
  var a, i, j, l, m, n, readints, res, x, z, z0, z1, zn, _i, _j, _k, _l, _len, _ref, _ref1, _results;

  readints = function() {
    var x, _i, _len, _ref, _results;
    _ref = readline().split(' ');
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      x = _ref[_i];
      _results.push(x | 0);
    }
    return _results;
  };

  _ref = readints(), n = _ref[0], m = _ref[1];

  a = (function() {
    var _i, _results;
    _results = [];
    for (_i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--) {
      _results.push(readline());
    }
    return _results;
  })();

  l = (function() {
    var _i, _results;
    _results = [];
    for (_i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--) {
      _results.push(0);
    }
    return _results;
  })();

  z = (function() {
    _results = [];
    for (var _i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--){ _results.push(_i); }
    return _results;
  }).apply(this);

  z1 = Array(n);

  res = 0;

  for (i = _j = _ref1 = m - 1; _ref1 <= 0 ? _j <= 0 : _j >= 0; i = _ref1 <= 0 ? ++_j : --_j) {
    zn = z0 = 0;
    for (_k = 0, _len = z.length; _k < _len; _k++) {
      x = z[_k];
      if (a[x][i] === '0') {
        l[x] = 0;
        z[z0++] = x;
      } else {
        l[x]++;
        z1[zn++] = x;
      }
    }
    for (j = _l = 0; 0 <= zn ? _l < zn : _l > zn; j = 0 <= zn ? ++_l : --_l) {
      res = Math.max(res, l[z1[j]] * (zn - j));
      z[z0++] = z1[j];
    }
  }

  print(res);

}).call(this);

// Generated by CoffeeScript 1.4.0
(function() {
  var a, i, j, l, m, n, readints, res, x, z, z0, z1, zn, _i, _j, _k, _l, _len, _ref, _ref1, _results;

  readints = function() {
    var x, _i, _len, _ref, _results;
    _ref = readline().split(' ');
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      x = _ref[_i];
      _results.push(x | 0);
    }
    return _results;
  };

  _ref = readints(), n = _ref[0], m = _ref[1];

  a = (function() {
    var _i, _results;
    _results = [];
    for (_i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--) {
      _results.push(readline().split(''));
    }
    return _results;
  })();

  l = (function() {
    var _i, _results;
    _results = [];
    for (_i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--) {
      _results.push(0);
    }
    return _results;
  })();

  z = (function() {
    _results = [];
    for (var _i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--){ _results.push(_i); }
    return _results;
  }).apply(this);

  z1 = Array(n);

  res = 0;

  for (i = _j = _ref1 = m - 1; _ref1 <= 0 ? _j <= 0 : _j >= 0; i = _ref1 <= 0 ? ++_j : --_j) {
    zn = z0 = 0;
    for (_k = 0, _len = z.length; _k < _len; _k++) {
      x = z[_k];
      if (a[x][i] === '0') {
        l[x] = 0;
        z[z0++] = x;
      } else {
        l[x]++;
        z1[zn++] = x;
      }
    }
    for (j = _l = 0; 0 <= zn ? _l < zn : _l > zn; j = 0 <= zn ? ++_l : --_l) {
      res = Math.max(res, l[z1[j]] * (zn - j));
      z[z0++] = z1[j];
    }
  }

  print(res);

}).call(this);

// Generated by CoffeeScript 1.4.0
(function() {
  var a, i, j, l, m, n, readints, res, x, z, z0, z1, zn, _i, _j, _k, _l, _len, _ref, _ref1, _results;

  readints = function() {
    var x, _i, _len, _ref, _results;
    _ref = readline().split(' ');
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      x = _ref[_i];
      _results.push(x | 0);
    }
    return _results;
  };

  _ref = readints(), n = _ref[0], m = _ref[1];

  a = (function() {
    var _i, _results;
    _results = [];
    for (_i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--) {
      _results.push(readline());
    }
    return _results;
  })();

  l = (function() {
    var _i, _results;
    _results = [];
    for (_i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--) {
      _results.push(0);
    }
    return _results;
  })();

  z = (function() {
    _results = [];
    for (var _i = 0; 0 <= n ? _i < n : _i > n; 0 <= n ? _i++ : _i--){ _results.push(_i); }
    return _results;
  }).apply(this);

  z1 = Array(n);

  res = 0;

  for (i = _j = _ref1 = m - 1; _ref1 <= 0 ? _j <= 0 : _j >= 0; i = _ref1 <= 0 ? ++_j : --_j) {
    zn = z0 = 0;
    for (_k = 0, _len = z.length; _k < _len; _k++) {
      x = z[_k];
      if (a[x].charAt(i) === '0') {
        l[x] = 0;
        z[z0++] = x;
      } else {
        l[x]++;
        z1[zn++] = x;
      }
    }
    for (j = _l = 0; 0 <= zn ? _l < zn : _l > zn; j = 0 <= zn ? ++_l : --_l) {
      res = Math.max(res, l[z1[j]] * (zn - j));
      z[z0++] = z1[j];
    }
  }

  print(res);

}).call(this);

function countingSort(arr, n){

    var min = arr[0];
    var max = arr[0];

    for(var i = 0; i < n; i++) {
        if(arr[i] < min ) {
            min = arr[i]
        } else if(arr[i] > max)
            max = arr[i]
    }

    var i = min;
    var j = 0;
    var len = arr.length;
    var count = [];

    for (var i = 0; i <= max; i++) {
        count[i] = 0;
    }
    for (var i = 0; i < len; i++) {
        count[arr[i]] += 1;
    }
    for (var i = min; i <= max; i++) {
        while (count[i] > 0) {
            arr[j] = i;
            j++;
            count[i]--;
        }
    }
    return arr;
}

var input = readline().split(' ');
var n = +input[0];
var m = +input[1];
// print(n)

var A = new Array(m + 1);
var copy = new Array(n).fill(0);
for (var i=0; i < A.length; i++){
    A[i] = copy.slice(0);
}

for (var i = 0; i < n; i++) {
    var row = readline().split('');
    for (var j = m - 1 ; j > -1; j--) {
        if(row[j] == '0') A[j][i] = 0;
        else {
            A[j][i] = Math.max(A[j + 1][i] + 1,A[j][i])
        }
    }
}

var maxArea = 0;
for (var i = 0; i < m; i++) {
    A[i] = countingSort(A[i],n);
    for (var j = 0; j < n; j++)
        if (A[i][j] * (n - j) > maxArea) maxArea = A[i][j] * (n - j)
}
print(maxArea);

var line = readline().split(' ');
var n = parseInt(line[0]);
var m = parseInt(line[1]);
var i, j, acc;
var counts = new Array(m);
for (j = 0; j < m; j++) {
  counts[j] = new Int16Array(5001);
}

for (i = 0; i < n; i++) {
  line = readline();
  acc = line[m-1] === '0' ? 0 : 1;
  counts[m-1][acc]++;
  for (j = m-2; j >= 0; j--) {
    if (line[j] === '1') {
      counts[j][++acc]++;
    } else {
      acc = 0;
    }
  }
}

var maxArea = 0;

for (j = 0; j < m; j++) {
  acc = 0;
  for (i = 5000; i > 0; i--) {
    acc += counts[j][i];
    if (acc*i > maxArea) {
      maxArea = acc*i;
    }
  }
}

print(maxArea);

function countingSort(arr, n){

    var min = arr[0];
    var max = arr[0];

    for(var i = 0; i < n; i++) {
        if(arr[i] < min ) {
            min = arr[i]
        } else if(arr[i] > max)
            max = arr[i]
    }

    var i = min;
    var j = 0;
    var len = arr.length;
    var count = [];

    for (var i = 0; i <= max; i++) {
        count[i] = 0;
    }
    for (var i = 0; i < len; i++) {
        count[arr[i]] += 1;
    }
    for (var i = min; i <= max; i++) {
        while (count[i] > 0) {
            arr[j] = i;
            j++;
            count[i]--;
        }
    }
    return arr;
}

var input = readline().split(' ');
var n = +input[0];
var m = +input[1];
// print(n)

var A = new Array(m + 1);
var copy = new Array(n).fill(0);
for (var i=0; i < A.length; i++){
    A[i] = copy.slice(0);
}

for (var i = 0; i < n; i++) {
    var row = readline().split('');
    for (var j = m - 1 ; j > -1; j--) {
        if(row[j] == '0') A[j][i] = 0;
        else {
            A[j][i] = Math.max(A[j + 1][i] + 1,A[j][i])
        }

    }
}

var maxArea = 0;
for (var i = 0; i < m - 1; i++) {
    A[i] = countingSort(A[i],n)
    for (var j = 0; j < n; j++)
        if (A[i][j] * (n - j) > maxArea) maxArea = A[i][j] * (n - j)
}
print(maxArea);

function countingSort(arr, n){
    var min = arr[0];
    var max = arr [0];

    for(i; i < n; i++) {
        if(arr[i] < min ) {
            min = arr[i]
        } else if(arr[i] > max)
            max = arr[i]
    }

    var i = min;
    var j = 0;
    var len = arr.length;
    var count = [];

    for (i; i <= max; i++) {
        count[i] = 0;
    }
    for (i = 0; i < len; i++) {
        count[arr[i]] += 1;
    }
    for (i = min; i <= max; i++) {
        while (count[i] > 0) {
            arr[j] = i;
            j++;
            count[i]--;
        }
    }
    return arr;
};

var input = readline().split(' ');
var n = +input[0];
var m = +input[1];
// print(n)

var A = {};

//  var row = readline().split('');

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

    var row = readline().split('');

    for (var j = 0; j < m; j++) {
        if (!A[j]) A[j] = [];
        if (row[j] == 0 || j == 0) { A[j][i] = Number(row[j]); continue; }
        A[j][i] = Math.max((A[j - 1][i] + 1), Number(row[j]));
    }
}

var maxArea = 0;
for (var i = 0; i < m; i++) {
    A[i] = countingSort(A[i],n)
    for (var j = 0; j < n; j++)
        if (A[i][j] * (n - j) > maxArea) maxArea = A[i][j] * (n - j)
}
print(maxArea);

var input = readline().split(' ');
var n = +input[0];
var m = +input[1];
// print(n)

var A = new Array(m + 1);
var copy = new Array(n).fill(0);
for (var i=0; i < A.length; i++){
    A[i] = copy.slice(0);
}

for (var i = 0; i < n; i++) {
    var row = readline().split('');
    for (var j = m - 1 ; j > -1; j--) {
        if(row[j] == '0') A[j][i] = 0;
        else {
            A[j][i] = Math.max(A[j + 1][i] + 1,A[j][i])
        }
    }
}

var maxArea = 0;
for (var i = 0; i < m; i++) {
    A[i].sort()
    for (var j = 0; j < n; j++)
        if (A[i][j] * (n - j) > maxArea) maxArea = A[i][j] * (n - j)
}
print(maxArea);

var line = readline().split(' ');
var n = parseInt(line[0]);
var m = parseInt(line[1]);
var rows = new Array(n);
var i, j;

for (i = 0; i < n; i++) {
  line = readline().split(' ');
  rows[i] = new Int8Array(m);
  rows[i][m-1] = parseInt(line[m-1]);
  for (j = m-2; j >= 0; j--) {
    if (line[j] === '1') {
      rows[i][j] = 1 + rows[i][j+1];
    }
  }
}

var maxArea = 0, area;
var cmp = function (a, b) {
  return a[j] - b[j];
};

for (j = 0; j < m; j++) {
  rows.sort(cmp);
  for (i = 0; i < n; i++) {
    area = (n-i)*rows[i][j];
    if (area > maxArea) {
      maxArea = area;
    }
  }
}

print(maxArea);


Polycarp got an array of integers $$$a[1 \dots n]$$$ as a gift. Now he wants to perform a certain number of operations (possibly zero) so that all elements of the array become the same (that is, to become $$$a_1=a_2=\dots=a_n$$$). In one operation, he can take some indices in the array and increase the elements of the array at those indices by $$$1$$$.For example, let $$$a=[4,2,1,6,2]$$$. He can perform the following operation: select indices 1, 2, and 4 and increase elements of the array in those indices by $$$1$$$. As a result, in one operation, he can get a new state of the array $$$a=[5,3,1,7,2]$$$.What is the minimum number of operations it can take so that all elements of the array become equal to each other (that is, to become $$$a_1=a_2=\dots=a_n$$$)?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)  — the number of test cases in the test. The following are descriptions of the input test cases. The first line of the description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$)  — the array $$$a$$$. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — elements of the array $$$a$$$.

For each test case, print one integer  — the minimum number of operations to make all elements of the array $$$a$$$ equal.

NoteFirst test case:   $$$a=[3,4,2,4,1,2]$$$ take $$$a_3, a_5$$$ and perform an operation plus one on them, as a result we get $$$a=[3,4,3,4,2,2]$$$.  $$$a=[3,4,3,4,2,2]$$$ we take $$$a_1, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,3,4,3,3]$$$.  $$$a=[4,4,3,4,3,3]$$$ we take $$$a_3, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,4,4,4,4]$$$. There are other sequences of $$$3$$$ operations, after the application of which all elements become equal.Second test case:   $$$a=[1000,1002,998]$$$ 2 times we take $$$a_1, a_3$$$ and perform an operation plus one on them, as a result we get $$$a=[1002,1002,1000]$$$.  $$$a=[1002,1002,1000]$$$ also take $$$a_3$$$ 2 times and perform an operation plus one on it, as a result we get $$$a=[1002,1002,1002]$$$. Third test case:   $$$a=[12,11]$$$ take $$$a_2$$$ and perform an operation plus one on it, as a result we get $$$a=[12,12]$$$.

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

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

        }
    }
});

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

let num = -1;
const rows = [];
rl.on('line', line => {
    if (num < 0) {
        num = parseInt(line.trim());
    } else {
        rows.push(line.trim());
        if (rows.length === num*2) {
            dealInput(rows);
        }
    }
});
const dealInput = (rows) => {
    let location = []
    rows.forEach(item => {
        location.push(item.split(' '))
    })
    location.forEach((item,index) => {
        if(index%2 !== 0) {
            let max = Math.max(...item)
            let min = Math.min(...item)
            console.log(max-min);
        }
    })
    rl.close();
};

rl.on('close', () => {
    process.exit(0);
});

let line = '';
process.stdin.on('data', c => line += c);
process.stdin.on('end', () => {
    let input = line.trim().split('\n');
    for (let i = 1; i < input.length;) {
        let arrayLength = input[i];
        i += 1;
        let row = input[i].split(' ').map(x => Number(x));
        row.sort((a, b) => a - b);
        console.log(row[arrayLength - 1] - row[0]);
        i += 1;
    }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function main() {
  let tests = parseInt(readline());
  while (tests--) {
    let len = parseInt(readline());
    let arr = readline().split(' ').map(Number);
    console.log(Math.max(...arr)-Math.min(...arr));
  }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function main() {
  let tests = parseInt(readline());
  while (tests--) {
    let len = parseInt(readline());
    let arr = readline()
      .split(' ')
      .map(Number)
      .sort((a, b) => {
        return a - b;
      });
    console.log(arr[len - 1] - arr[0]);
  }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function main() {
  let tests = parseInt(readline());
  while (tests--) {
    let len = parseInt(readline());
    let arr = readline()
      .split(' ')
      .sort((a, b) => {
        return a - b;
      });
    console.log(arr[len - 1] - arr[0]);
  }
}

let line = '';
process.stdin.on('data', c => line += c);
process.stdin.on('end', () => {
    let input = line.trim().split('\n');
    for (let i = 1; i < input.length;) {
        const arrayLength = input[i];
        i += 1;
        let row = input[i].split(' ').map(x => Number(x));
        row.sort((a, b) => a - b);
        console.log(row[arrayLength - 1] - row[0]);
        i += 1;
    }
});

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    let line=buf.split('\n');
    let t=parseInt(line[0]);
    for(let i=1;i<=2*t;i+=2)
    {
        let arr=line[i+1].split(' ').map(x=>{ return parseInt(x) });
        let mx=0;
        let mn=1e10;
        for(let j=0;j<arr.length;j++)
        {
            mx=Math.max(mx,arr[j]);
            mn=Math.min(mn,arr[j]);
        }
        console.log(mx-mn);
    }
})

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    let line=buf.split('\n');
    let t=parseInt(line[0]);
    for(let i=1;i<=2*t;i+=2)
    {
        let arr=line[i+1].split(' ').map(x=>{ return parseInt(x) });
        let mx=0;
        let mn=1e10;
        for(let j=0;j<arr.length;j++)
        {
            mx=Math.max(mx,arr[j]);
            mn=Math.min(mn,arr[j]);
        }
        // let ans=0;
        // console.log(mx);
        // for(let j=0;j<arr.length;j++)
        // {
        //     ans+=mx-arr[j];
        // }
        console.log(mx-mn);
        // console.log(arr);
    }
    // console.log(line);
})

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++){
		nl.num();
		let a = nl.nums();
		//let min = a.reduce((a, b) => (a < b)?a:b, 1000000000);
		//let max = a.reduce((a, b) => (a > b)?a:b, 0);
		let min = Math.min.apply(null, a);
		let max = Math.max.apply(null, a);
		ans.push(max - min);
	}
	console.log(ans.join('\n'));
};

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

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++){
		nl.num();
		let a = nl.nums();
		let min = a.reduce((a, b) => (a < b)?a:b, 1000000000);
		let max = a.reduce((a, b) => (a > b)?a:b, 0);
		ans.push(max - min);
	}
	console.log(ans.join('\n'));
};

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

let data = "";

process.stdin.on("data", (c) => (data += c));
process.stdin.on("end", () => {
  let [_, ...input] = data
    .trim()
    .split(/\n/)
    .map((el) => el.trim());

  input = input.filter((el, idx) => idx % 2 !== 0);

  input = input.map((el) =>
    el
      .trim()
      .split(" ")
      .map((el) => +el.trim())
      .sort((a, b) => a - b)
  );

  input.forEach((el) => {
    console.log(el[el.length - 1] - el[0]);
  });
});

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 % 2 !== 0) {
    c++;
    return;
  }

  const digits = d.split(" ").map(Number);
  const min = Math.min(...digits);
  const max = Math.max(...digits);
  console.log(max - min);

  c++;
});

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

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

let input = [];
let ans = [];

readline.on('line', line => {
    input.push(line);
}).on('close', () => {
    for (let i = 2; i < input.length; i+=2) {
        let nums = input[i].split(' ').map(Number);
        let [min, max] = [Math.min(...nums), Math.max(...nums)];
        ans.push(max-min);
    }
    console.log(ans.join('\n'));
});

// 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, arr) => {
    if( n == 1 ) return 0
    if( n == 2 ) return Math.abs( arr[0] - arr[1] )

    arr = sortArray( arr )

    let min = minOfArray( arr )
    let max = maxOfArray( arr )

    return max - min
}

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)

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 e = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            e = lines[i];
        }else{
            var k = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});
            console.log(k[e - 1] - k[0]);
        }
    }
});

//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] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}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 nextDoubleArray(size){return nextArray(size, 'double');}
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 nextDouble(){return parseFloat(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 max = 0;
		var min = Math.pow(10, 9) + 1;
		for(var i = 0; i < N; i++){
			max = Math.max(max, list[i]);
			min = Math.min(min, list[i]);
		}
		myout(max - min);
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    let t = parseInt(readLine());
    while (t-- > 0) {
        solve();
    }
}

let count=0;
function solve() {
    let str = readLine();

    let c = readLine();

    var d = c.split(' ');
    var digits = d.map(iNum => parseInt(iNum, 10));

    count = Math.max(...digits) - Math.min(...digits);
    console.log(count)

}

var i = -1
require('readline').createInterface(process.stdin,process.stdout).on('line', (line) => {
  if (++i && !(i%2)) {
    const a = line.split(" ").map(Number);
    console.log(Math.max(...a) - Math.min(...a))
  };
});

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++];
    for (let i = 0; i < testCases; i++) {
        let arrSize = +input[z++];
        let arr = input[z++].split(' ').map(t=>Number(t));
        let max = Math.max(...arr);
        let min = Math.min(...arr);
        console.log(max-min);
    }
}

/*
===== READ INPUT DATA START =====
=================================
*/

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

let inputString = '';

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

process.stdin.on('end', (_) => {
  const lines = inputString.trim().split('\n').map((string) => string.trim()).filter(Boolean);
  main(lines);
});

/*
===== READ INPUT DATA END =====
===============================
*/

function main(lines) {
  let index = 0;
  let T = Number(lines[index++]);
  let N;
  let arr;

  while (T--) {
    N = Number(lines[index++]);
    arr = lines[index++].split(' ').map(Number);
    solve(N, arr);
  }
}

function solve(N, arr) {
  const [minVal, maxVal] = [Math.min(...arr), Math.max(...arr)];

  console.log(maxVal - minVal);
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});
function readLine() {
  return inputString[currentLine++];
};
process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });
  main();
  // cmd: node cp.js < input.txt > output.txt
});
function main() {
  let t = parseInt(readLine());
  while (t--) {
    solve();
  }
}
function solve() {
  let len=readLine();
  let arr=readLine().split(" ");
  arr.sort((a,b)=>parseInt(a)-parseInt(b));;
  console.log(arr[len-1]-arr[0]);
}

let _inputLines;
let _lineNumber = 0;
let inputReader = _inputReader ();

function _main() {

	_inputLines = _inputData.trim().split('\n').map((string) => {
		return string.trim();
	});;

	let t = inputReader.readNumber();

	function solve(){
	    let n = inputReader.readNumber();
	    let a = inputReader.readArray();
	    let max = Math.max(...a);
	    let min = Math.min(...a);
	    console.log(max - min);
	}

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

}

var _inputData = '';
function cacheInput(data) {
	_inputData += data;
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', cacheInput).on('end', _main);

function _inputReader () {
	function readArray() {
		return _inputLines[_lineNumber++].split(' ');
	}

	function readNumber(){
		return Number(_inputLines[_lineNumber++]);
	}

	return {
		readArray,
		readNumber,
	}
}

var di
var stdin_input = ""
process.stdin.resume()
process.stdin.setEncoding("ascii")
process.stdin.on("data", (input) => { stdin_input += input })
process.stdin.on("end", () => { main() })

const rl = () => di.next().value.trim(); //Read line
const rn = () => +rl(); //Read number
const ra = () => rl().split(' '); //Read array
const rna = () => ra().map(x => +x); //Read array of numbers
const l = i => {console.log(i)} //Return answer

const main = () => {
  di = stdin_input.split('\n').values()
  let T = rn();
  while (T--) {
    const _ = rn();
    const a = rna();
    l(Math.max(...a) - Math.min(...a));
	}
}

/* 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) => {
            return string.trim();
        });

    main();
});

function readline() {
    return inputString[currentLine++];
}
/* Common Template Ends */

function main() {
    //take input according to the format;
    const t = +(readline());
    for(let i =0; i<t; ++i){
        const n = +(readline());
        const arr = readline().split(' ');

        plusOneSubset(arr)

    }
}
const plusOneSubset= (arr)=>{

    let arrNum = arr.map(el=>parseInt(el));

    arrNum.sort((a,b)=>a-b);

    let cSum = 0;
    for(let i =0; i+1<arrNum.length; ++i){
        cSum+= arrNum[i+1] - arrNum[i];
    }
    console.log(cSum);
}

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*/

    let count = 2;
    for (let i = 0; i < lines[0]; ++i) {
        let total = 0;
        const arr = lines[count].split(' ').map((el) => +el);

        arr.sort((a, b) => b - a);

        const len = arr.length;

        if (len > 1) {
            const max = arr[0];
            for (let i = 1; i < len; ++i) {
                const curDiff = max - arr[i];
                total += curDiff;
                for (let j = i + 1; j < len; ++j) {
                    arr[j] += curDiff;
                }
            }
        }
        console.log(total);

        count += 2;
    }
});

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

var T = readline();
for(var q=1;q<=T;q++) {
    let n = readline();
    let a = readline().split(" ").map(w => parseInt(w))
    var max = -1, min = 100000000000;
    for(var i=0;i<a.length;i++) {
      max = Math.max(max, a[i])
	  min = Math.min(min,a[i])
    }
    console.log(max-min)
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => {
        let next;
        do {
            next = (await getLineGen.next());
        } while (!next.done && next.value === '');
        return next.value;
    };
})();

const readInt = async function(){
    return parseInt(await getLine());
}

const readIntArray = async function() {
    return (await getLine()).split(' ').map(num => parseInt(num));
}

let solve = async () => {
    const tsc = await readInt();
    for(let sc = 0; sc < tsc; sc++) {
        const n = await readInt();
        const a = await readIntArray();
        a.sort((a,b) => a - b);
        console.log(a[a.length - 1] - a[0]);
    }
}

solve();

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

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

let count = -1
let inputArr = []

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

function solve([n], arr) {
    const sarr = arr.sort((a, b) => a - b)
    const max = sarr[0], min = sarr[sarr.length - 1]
    console.log(Math.abs(min - max))
}

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

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) {
    arr.sort((a, b) => a - b)
    return arr[n - 1] - arr[0]
}

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

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

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

		const ans = Math.max(...a) - Math.min(...a);

		console.log(ans);
	}
}

test = readline();
while (test--) {
    readline();
    set = new Set()
    readline().split(' ').map(x => set.add(parseInt(x)));
    max = Math.max(...set);
    set = Array.from(set).sort((a, b) => b - a)
    steps = 0;
    set.forEach(num => {
        if (num < max) {
            num += steps
            steps += (max - num)
        }
    })
    print(steps)
}

j = +readline();
while (j--) {
  x = +readline();
  t = readline().split(" ").map(Number);
  if (t.length > 1) {
    q = Math.max(...t);
    w = Math.min(...t);
    c = q - w;
    print(c);
  } else {
    print(0);
  }
}

var tests=+readline()
for(var i=0;i<tests;i++){
var length=+readline()
var sequence=readline().split(" ").map(node=>+node)
sequence.sort((a,b)=>{
    return a-b
})
print((sequence[length-1]-sequence[0]))
}

var tests=+readline()
for(var i=0;i<tests;i++){
var length=+readline()
var sequence=readline().split(" ").map(node=>+node)
var min=sequence.reduce((a,b)=>Math.min(a,b))
var max=sequence.reduce((a,b)=>Math.max(a,b))

print((max-min))
}

'use strict'

const getLine = () => readline().split(' ')
const getInts = () => getLine().map(n => parseInt(n))
const getInt = () => getInts()[0]
const D = (...args) => { // D({name})
  [...args].forEach(cur => print.apply(print, [JSON.stringify(cur)]))
}

main()

function main() {
    const TC = getInt();
    for (let i = 0; i < TC; ++i) {
        const n = getInt();
        const arr = getInts();

        arr.sort((a, b) => a - b);
        print(arr[n - 1] - arr[0])
    }

}

var count = parseInt(readline());

while (count--){
   var n = readline();
   var n1 = readline()
   var arr = n1.split(' ').map(Number)
   print(Math.max(...arr) - Math.min(...arr))
}

var t = parseInt(readline());

  function solve() {
    var n = parseInt(readline());
    var a = readline().split(" ").map((data) => +data)
    var max = -Infinity
    var min = Infinity
    for (var i = 0; i < n; i++) {
      max = Math.max(max, a[i])
      min = Math.min(min, a[i])
    }
    return max - min;
  }

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

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

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(j = 1; j <= n * 2; j++){
        if(j % 2 == 1){
            var a = Number(lines[j])
            if(a % 2 === 0){
                console.log(a / 2)
            }else{
                console.log(a += 1)
            }
        }
    }
});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(j = 1; j <= n; j++){
        if(j % 2 == 1){
            var a = Number(lines[j])
            if(a % 2 === 0){
                console.log(a / 2)
            }else{
                console.log(a += 1)
            }
        }
    }
});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(j = 1; j <= n; j++){
        if(j % 2 == 1){
            var a = lines[j]
            if(a % 2 === 0){
                console.log(a / 2)
            }else{
                console.log(a += 1)
            }
        }
    }
});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(j = 1; j <= n; j++){
        if(j % 2 == 1){
            var a = lines[j]
            if(a % 2 === 0){
                console.log(a / 2)
            }else{
                console.log(a + 1)
            }
        }
    }
});

let line = '';
let rows = [];
process.stdin.on('data', c => line += c);
process.stdin.on('end', () => {
    const lines = line.split('\n');
    let input1 = +lines[0];

    for (let i = 1; i <= input1; i++) {
        let row = lines[i].split(' ');
        row.sort((a, b) => a - b);
        console.log(row[row.length - 1] - row[0]);
    }

});

j = +readline();
while (j--) {
  x = +readline();
  t = readline().split(" ").map(Number);
  if (t.length > 1) {
    q = Math.max(...t);
    w = Math.min(...t);
    c = q - w;
    print(c);
  } else {
    print(1);
  }
}

j = +readline();
while (j--) {
  x = +readline();
  t = readline().split(" ").map(Number);
  if (x > 1) {
    q = Math.max(...t);
    w = Math.min(...t);
    c = q - w;
    print(c);
  } else {
    print(1);
  }
}


There is a city that can be represented as a square grid with corner points in $$$(0, 0)$$$ and $$$(10^6, 10^6)$$$.The city has $$$n$$$ vertical and $$$m$$$ horizontal streets that goes across the whole city, i. e. the $$$i$$$-th vertical streets goes from $$$(x_i, 0)$$$ to $$$(x_i, 10^6)$$$ and the $$$j$$$-th horizontal street goes from $$$(0, y_j)$$$ to $$$(10^6, y_j)$$$. All streets are bidirectional. Borders of the city are streets as well.There are $$$k$$$ persons staying on the streets: the $$$p$$$-th person at point $$$(x_p, y_p)$$$ (so either $$$x_p$$$ equal to some $$$x_i$$$ or $$$y_p$$$ equal to some $$$y_j$$$, or both).Let's say that a pair of persons form an inconvenient pair if the shortest path from one person to another going only by streets is strictly greater than the Manhattan distance between them.Calculate the number of inconvenient pairs of persons (pairs $$$(x, y)$$$ and $$$(y, x)$$$ are the same pair).Let's recall that Manhattan distance between points $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n, m \le 2 \cdot 10^5$$$; $$$2 \le k \le 3 \cdot 10^5$$$) — the number of vertical and horizontal streets and the number of persons. The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 = x_1 < x_2 < \dots < x_{n - 1} < x_n = 10^6$$$) — the $$$x$$$-coordinates of vertical streets. The third line contains $$$m$$$ integers $$$y_1, y_2, \dots, y_m$$$ ($$$0 = y_1 < y_2 < \dots < y_{m - 1} < y_m = 10^6$$$) — the $$$y$$$-coordinates of horizontal streets. Next $$$k$$$ lines contains description of people. The $$$p$$$-th line contains two integers $$$x_p$$$ and $$$y_p$$$ ($$$0 \le x_p, y_p \le 10^6$$$; $$$x_p \in \{x_1, \dots, x_n\}$$$ or $$$y_p \in \{y_1, \dots, y_m\}$$$) — the coordinates of the $$$p$$$-th person. All points are distinct. It guaranteed that sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$, sum of $$$m$$$ doesn't exceed $$$2 \cdot 10^5$$$ and sum of $$$k$$$ doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, print the number of inconvenient pairs.

NoteThe second test case is pictured below:   For example, points $$$3$$$ and $$$4$$$ form an inconvenient pair, since the shortest path between them (shown red and equal to $$$7$$$) is greater than its Manhattan distance (equal to $$$5$$$).Points $$$3$$$ and $$$5$$$ also form an inconvenient pair: the shortest path equal to $$$1000001$$$ (shown green) is greater than the Manhattan distance equal to $$$999999$$$.But points $$$5$$$ and $$$9$$$ don't form an inconvenient pair, since the shortest path (shown purple) is equal to its Manhattan distance.

const readline = require('readline')

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

function solve(n, m, k, xs, ys, arr) {
    const mx = xs.reduce((o, x) => {
        o[x] = 1
        return o
    }, {})
    const my = ys.reduce((o, x) => {
        o[x] = 1
        return o
    }, {})

    const gx = {}
    const gy = {}
    arr.forEach(([x, y]) => {
        if (!mx[x]) {
            const idx = binarySearch(0, xs.length - 1, i => xs[i] < x)
            gy[idx] = gy[idx] || []
            gy[idx].push(y)
        }
        if (!my[y]) {
            const idx = binarySearch(0, ys.length - 1, i => ys[i] < y)
            gx[idx] = gx[idx] || []
            gx[idx].push(x)
        }
    })
// console.log(gx, gy)
    let sum = 0
    for (let idx in gx) {
        const count = gx[idx].reduce((o, x) => {
            o[x] = (o[x] || 0) + 1
            return o
        }, {})
        let add = 0
        for (let x in count) {
            add += count[x] * (gx[idx].length - count[x])
        }
        sum += add / 2
    }
    for (let idx in gy) {
        const count = gy[idx].reduce((o, x) => {
            o[x] = (o[x] || 0) + 1
            return o
        }, {})
        let add = 0
        for (let x in count) {
            add += count[x] * (gy[idx].length - count[x])
        }
        sum += add / 2
    }
    return sum
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}


DZY loves chemistry, and he enjoys mixing chemicals.DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.Find the maximum possible danger after pouring all the chemicals one by one in optimal order.

The first line contains two space-separated integers n and m . Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input. Consider all the chemicals numbered from 1 to n in some order.

Print a single integer — the maximum possible danger.

NoteIn the first sample, there's only one way to pour, and the danger won't increase.In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).

function bfs(s, adj, visited) {
    var q = [];
    var pos = 0;
    q.push(s);
    visited[s] = true;
    while (pos < q.length) {
        var u = q[pos++];
        adj[u].forEach(function (v) {
            if (!visited[v]) {
                q.push(v);
                visited[v] = true;
            }
        });
    }
    return q.length;
}

var a = readline().split(" ").map(function (x) { return parseInt(x); });
var n = a[0], m = a[1];
var adj = [];
for (i = 0; i <= n; ++i) {
    adj.push([]);
}
for (i = 0; i < m; ++i) {
    a = readline().split(" ").map(function (x) { return parseInt(x); });
    adj[a[0]].push(a[1]);
    adj[a[1]].push(a[0]);
}
var visited = new Array(n + 1);
for (i = 0; i <= n; ++i) {
    visited[i] = false;
}
r = 1;
for (i = 1; i <= n; ++i) {
    if (!visited[i]) {
        var p = bfs(i, adj, visited);
        for (j = 1; j < p; ++j) {
            r = r * 2;
        }
    }
}
print(r);

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

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

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

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], m = data[1],
		edges = {}, vertices = [];
	edges.add = function (u, v) {
		if (edges[u] === undefined) {
			edges[u] = [v];
			vertices.push(u);
		} else {
			edges[u].push(v);
		}
	};
	for (var i = 0; i < m; ++i) {
		var pair = tokenizeIntegers(readline()),
			u = pair[0], v = pair[1];
		edges.add(u, v);
		edges.add(v, u);
	}
	var seen = {}, danger = 1;
	function dfs(u, double) {
		if (seen[u]) {
			return;
		}
		seen[u] = true;
		if (double) {
			danger *= 2;
		}
		var vs = edges[u];
		for (var i = 0; i < vs.length; ++i) {
			dfs(vs[i], true);
		}
	}
	for (var i = 0; i < vertices.length; ++i) {
		var u = vertices[i];
		dfs(u, false);
	}
	print(danger);
}

main();


You are given a tree (an undirected connected graph without cycles) and an integer $$$s$$$.Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is $$$s$$$. At the same time, he wants to make the diameter of the tree as small as possible.Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.Find the minimum possible diameter that Vanya can get.

The first line contains two integer numbers $$$n$$$ and $$$s$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq s \leq 10^9$$$) — the number of vertices in the tree and the sum of edge weights. Each of the following $$$n−1$$$ lines contains two space-separated integer numbers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the indexes of vertices connected by an edge. The edges are undirected. It is guaranteed that the given edges form a tree.

Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to $$$s$$$. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\frac {|a-b|} {max(1, b)} \leq 10^{-6}$$$.

NoteIn the first example it is necessary to put weights like this:  It is easy to see that the diameter of this tree is $$$2$$$. It can be proved that it is the minimum possible diameter.In the second example it is necessary to put weights like this:

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString='';
let currentLine=0;
process.stdin.on('data',inputStdin=>{
	inputString+=inputStdin;
});
process.stdin.on('end',_=>{
	inputString=inputString.trim().split("\n").map(string=>{
		return string.trim();
	});
	main();
});
function readLine()
{
	return inputString[currentLine++];
}
function main()
{
	// const N=parseInt(readLine());
	const [n,s]=readLine().trim().split(" ").map(x=>{return +(x);});
	var mp=[];
	for(let i=0;i<n;++i)
		mp.push(0);
	for(let i=0;i<n-1;++i)
	{
		let [u,v]=readLine().trim().split(" ").map(x=>{return +(x);});
		u--;
		v--;
		mp[u]++;
		mp[v]++;
	}
	let lf=0;
	for(let i=0;i<n;++i)
	{
		if(mp[i]==1)
			lf++;
	}
	let ans=(s*2)/lf;
	console.log(ans);
}


A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

The first input line contains the only integer n (2 ≤ n ≤ 100) which represents the number of soldiers in the line. The second line contains integers a1, a2, ..., an (1 ≤ ai ≤ 100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1, a2, ..., an are not necessarily different.

Print the only integer — the minimum number of seconds the colonel will need to form a line-up the general will like.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  const len = +readLine();
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  let [minIndex, maxIndex] = [-1, -1];
  let [min, max] = [Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER];

  for (let i = 0; i < len; i++) {
    if (arr[i] > max) {
      max = arr[i];
      maxIndex = i;
    }
    if (arr[i] <= min) {
      min = arr[i];
      minIndex = i;
    }
  }
  const moves = maxIndex + (len - 1 - minIndex);
  if (moves > len - 2) {
    console.log(moves - 1);
  } else {
    console.log(moves);
  }
}

var n=+readline();
var a=readline().split(' ').map(function(v){return+v;});
var min=Math.min.apply(null, a);
var max=Math.max.apply(null, a);
var minIndex = a.lastIndexOf(min);
a.splice(minIndex,1);
a.push(min);
var maxIndex = a.indexOf(max);
print( n-minIndex-1+maxIndex );

var n = +readline(), line = readline().split(" "), sorted = [], cmax, cmin, buf;
line.forEach(function(a){
	sorted.push(+a);
})
sorted.sort(function(a,b){return a-b});

cmin = line.lastIndexOf(sorted[0].toString(10));
cmax = line.indexOf(sorted[n-1].toString(10));

for(i = 1;  ; i++){
	if( cmax > 0 ){
		buf = line[cmax-1];
		line[cmax-1] = line[cmax];
		line[cmax] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
	}
	else if( cmin < n-1 ){
		buf = line[cmin+1];
		line[cmin+1] = line[cmin];
		line[cmin] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
	}
	if( (cmax == 0) && (cmin == n-1) ){
		write( (buf != undefined) ? i : i-1 );
		break;
	}
}

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input))+1;
var max_index = input.indexOf(Math.max(...input))+1;
var output;
if(min_index < max_index){
    output = input.length-min_index+max_index-2;
}else{
    output = input.length-min_index+max_index-1;
}
print(output);

;(function () {

	var s = (readline(), readline()).split(' ').map(function (x) {return parseInt(x);});

	var max = Math.max.apply(null, s);
	var min = Math.min.apply(null, s);

	for (var i = 0; i < s.length; i++) if (max == s[i]) break;
	for (var j = s.length - 1; j >= 0; j--) if (min == s[j]) break;

	print(i + ( s.length - j - 1 ) - ( i > j));

}).call(this);

'use strict';

let n = parseInt(readline());
let array = readline().split(' ').map(value => parseInt(value));

let max = array[0],
    min = array[0],
    time = 0;

for(let i = 0; i < array.length; i++){
    if (array[i] > max) {
        max = array[i];
    }

    if (array[i] < min) {
        min = array[i];
    }
}

let maxPosition = array.indexOf(max);

for(let i=maxPosition; i > 0; i--) {
    time++;
    let temp = array[i];
    array[i] =  array[i - 1];
    array[i - 1] = temp;
}

let minPosition = array.reverse().indexOf(min);

write(time + minPosition);

var n  = readline();//.split(" ");
var str  = readline().split(" ").map((x)=>+x);
var min = Math.min.apply(this, str); var max = Math.max.apply(this, str);
var MinIndex = str.lastIndexOf(min)+1; var MaxIndex = str.indexOf(max)+1;

print(min==+str[str.length-1]&&max==+str[0]? 0:
MaxIndex>MinIndex? MaxIndex-1+str.length-MinIndex-1:MaxIndex-1+str.length-MinIndex);

var n = parseInt(readline());
var soldiers = readline().split(' ').map(function(num){return parseInt(num)});
var max = Math.max(...soldiers);
var min = Math.min(...soldiers);
var indexOfMax = soldiers.indexOf(max);
var indexOfMin = soldiers.lastIndexOf(min);
var swaps = (n - (indexOfMin  + 1)) + (indexOfMax);
if(indexOfMax > indexOfMin) swaps--;
print(swaps);

var n = Number(readline());
var s = readline().split(' ').map(Number);

var max = Math.max.apply(null, s);
var min = Math.min.apply(null, s);

for (var i = 0; i < n; i++) {
    if (max === s[i]) {
        break;
    }
}
for (var j = n - 1; j >= 0; j--) {
    if (min === s[j]) {
        break;
    }
}

print(i + ( n - j - 1 ) - ( i > j));

var n = parseInt(readline());
var a = readline().split(" ").map(function(x) { return parseInt(x); });
var time = 0;
var min_p = 0;
var min_v = 999;
var max_p = 0;
var max_v = 0;

for (var i = 0; i < a.length; i++){
  if (min_v >= a[i]) {
   min_v = a[i];
   min_p = i;
  }
  if (max_v < a[i]) {
   max_v = a[i];
   max_p = i;
  }
}

if (max_p > min_p) {
	time = max_p + (a.length - 1 - min_p) - 1;
} else {
	time = max_p + (a.length - 1 - min_p);
}

print (time);

var computeSoldiersForGeneral = function(arr)
{
    arr = arr.split(' ');
    var indexMax = 0, indexMin = 0;
    for (var i = 1; i <= arr.length - 1; i++)
    {
        if (+arr[i] > +arr[indexMax]) indexMax = i;
        if (+arr[i] <= +arr[indexMin]) indexMin = i;
    }
    if (indexMax > indexMin) return indexMax + arr.length - indexMin - 2;
    else return indexMax + arr.length - indexMin - 1;
}
var input1 = readline();
var input = readline();
print(computeSoldiersForGeneral(input));

var n = readline();
var soliders = readline().split(" ");

var maxIndex = 0;
var minIndex = 0;
var swapTime = 0;

for(var i = 0; i < n; i++){
	maxIndex = (parseInt(soliders[i]) > parseInt(soliders[maxIndex])) ? i : maxIndex;
	minIndex = (parseInt(soliders[i]) <= parseInt(soliders[minIndex])) ? i : minIndex;
}
if(maxIndex > minIndex)
	swapTime = (parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex))-1);
else
	swapTime = parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex));
print(swapTime);

//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 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 N = nextInt();
  var list = nextIntArray();
  var min = 101;
  var max = 0;
  var minIndex = -1;
  var maxIndex = -1;
  for(var i = 0; i < N; i++){
    if(min >= list[i]){
      min = list[i];
      minIndex = i;
    }
  }
  for(var i = N - 1; i >= 0; i--){
    if(max <= list[i]){
      max = list[i];
      maxIndex = i;
    }
  }
  if(maxIndex > minIndex){
    myout(maxIndex + (N - minIndex - 1) - 1);
  }else{
    myout(maxIndex + (N - minIndex - 1));
  }
}

const readline = require('readline');

let inputs = [];

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

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    let arr = inputs[1].split(' ').map(num => parseInt(num));
    let Pmax = arr.indexOf(Math.max(...arr));
    let Pmin = 0;
    let limiter = 0;
    const shortestHeight = Math.min(...arr);

    for (let i = arr.length; i > 0; i--) {
        if (arr[i] == shortestHeight && limiter == 0) {
            Pmin = i;
            limiter++
        }
    }

    let minSeconds;

    Pmin = parseInt(Pmin)
    Pmax = parseInt(Pmax)

    if (Pmin < Pmax) {
        minSeconds = Pmax + (arr.length - 1 - Pmin) - 1;
    } else {
        minSeconds = Pmax + (arr.length - 1 - Pmin);
    }

    console.log(minSeconds);

})

const readline = require('readline');

let inputs = [];

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

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    let arr = inputs[1].split(' ');
    let Pmax = arr.indexOf(Math.max(...arr).toString());
    let Pmin = 0;
    let limiter = 0;
    const shortestHeight = Math.min(...arr).toString();

    for (let i = arr.length; i > 0; i--) {
        if (arr[i] == shortestHeight && limiter == 0) {
            Pmin = i;
            limiter++
        }
    }

    let minSeconds;

    Pmin = parseInt(Pmin)
    Pmax = parseInt(Pmax)

    if (Pmin < Pmax) {
        minSeconds = Pmax + (arr.length - Pmin) - 2;
    } else {
        minSeconds = Pmax + (arr.length - 1 - Pmin);
    }

    console.log(minSeconds);

})

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

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

readLine.on('close', () => {
    const a = input[1].split(' ').map(x => +x);
    let imax = 0;
    let imin = 0;
    for (let i = 1; i < a.length; i++) {
        if (a[i] > a[imax]) {
            imax = i;
        }
        else if (a[i] <= a[imin]) {
            imin = i;
        }
    }
    const maxSteps = imax;
    const minSteps = a.length - imin - 1;
    const commonSteps = +(imax > imin);
    console.log(maxSteps + minSteps - commonSteps);
});

//Arrival of the General

const {EOL} = require('os');

let inp = '';

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

process.stdin.on('end', () => {
    let lines = inp.split(EOL)[1].split(' ').map(c => +c);

    let maxi = 0, mini = 0;
    for(let i = 0; i < lines.length; i++)  {
    	if(lines[i] <= lines[mini])  {
    		mini = i;
    	}
    	if(lines[i] > lines[maxi])  {
    		maxi = i;
    	}
    }

    if(maxi > mini)  {
    	process.stdout.write((maxi + lines.length - mini - 2) + '');
    }  else  {
    	process.stdout.write((maxi + lines.length - mini - 1) + '');
    }

    return;
});

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

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

  const arr = d.split(' ').map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  const idxMin = arr.lastIndexOf(min);
  const idxMax = arr.indexOf(max);

  ans += idxMax;

  if (idxMin > idxMax) {
    ans += Math.max(arr.length - idxMin - 1, 0);
  }
  else {
    ans += Math.max(arr.length - idxMin - 2, 0);
  }

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

const input = [];

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

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

RL.on('close', () => {
    const nums = input[1].split(' ').map(x => parseInt(x));
    let min = 1000, minIndex = -1;
    let max = 0, maxIndex = -1;
    nums.forEach((x, i) => {
      if (x > max) {max = x; maxIndex = i}
      if (x <= min) {min = x; minIndex = i}
    });

    if (maxIndex < minIndex)
      console.log(maxIndex + nums.length - (minIndex + 1));
    else
      console.log(maxIndex + nums.length - (minIndex + 1) - 1);
});

const readline = require('readline');

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

rl.on('line', input => {
  rl.on('line', input2 => {
    console.log(min(input2.split(' ').map(n => parseInt(n))));
    process.exit();
  });
});

const min = input => {
  const min = Math.min(...input);
  const max = Math.max(...input);
  let iMin = input.lastIndexOf(min);
  let iMax = input.findIndex(e => e == max);
  let secs = 0;
  let temp = 0;

  while(input[input.length-1] !== min) {
    if(input[iMin+1] !== min) {
      temp = input[iMin+1];
      input[iMin+1] = input[iMin];
      input[iMin] = temp;
      secs++;
    }
    iMin++;
  }

  while(input[0] !== max) {
    if(input[iMax-1] !== max) {
      temp = input[iMax-1];
      input[iMax-1] = input[iMax];
      input[iMax] = temp;
      secs++;
    }
    iMax--;
  }

  return secs;
}

const readline = require('readline');

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

rl.on('line', input => {
  rl.on('line', input2 => {
    console.log(min(input2.split(' ').map(n => parseInt(n))));
    process.exit();
  });
});

const min = input => {
  const min = Math.min(...input);
  const max = Math.max(...input);
  let iMin = input.lastIndexOf(min);
  let iMax = input.findIndex(e => e == max);
  let secs = 0;
  let temp = 0;
  const length = input.length - 1;

  return iMin > iMax ? length - iMin + iMax : length - 1 - iMin + iMax;

  // while(input[input.length-1] !== min) {
  //   if(input[iMin+1] !== min) {
  //     temp = input[iMin+1];
  //     input[iMin+1] = input[iMin];
  //     input[iMin] = temp;
  //     secs++;
  //   }
  //   iMin++;
  // }

  // while(input[0] !== max) {
  //   if(input[iMax-1] !== max) {
  //     temp = input[iMax-1];
  //     input[iMax-1] = input[iMax];
  //     input[iMax] = temp;
  //     secs++;
  //   }
  //   iMax--;
  // }

  // return secs;
}

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function isPrime(x) {
	let s = Math.sqrt(x);
	let i = 2;
	while (i <= s) {
		if (x % i === 0) {
			return false;
		}
		i++;
	}
	return true;
}

function main() {
	let n = readLine() >> 0;
	let sol = readLine()
		.split(' ')
		.map(x => x >> 0);

	let sc = 0;

	let min = Math.min(...sol);
	let max = Math.max(...sol);
	let posMax = 0,
		posMin = 0;

	sol.forEach((x, i) => {
		if (x === min && i >= posMin) posMin = i + 1;
		if (x === max && posMax === 0) posMax = i + 1;
	});

	sc = n - posMin;
	if (posMax > posMin) sc += posMax - 2;
	else sc += posMax - 1;

	console.log(sc);
}

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

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

readline.on('close', () => {
    const arr = input[1].split(' ').map(Number);
    let min = 101, max = 0;
    arr.forEach(v => {
        if (v < min) min = v;
        if (v > max) max = v;
    });
    let minpos = -1, maxpos = 101;
    arr.forEach((v, i) => {
        if (v == min && i > minpos) minpos = i;
        if (v == max && i < maxpos) maxpos = i;
    });
    let dist = 0;
    if (minpos < maxpos) dist -= 1;
    dist += arr.length - minpos - 1;
    dist += maxpos;
    console.log(dist);
});

let fs = require('fs');

let txt = fs.readFileSync(0, "utf-8").split("\n").filter(data => data.length > 0);
for (let i = 0; i < txt.length; i += 2) {
    doit(txt[i + 1].split(" ").filter(data => data.length > 0).map(data => data * 1));
}

function doit(tab) {
    let max = tab.indexOf(Math.max(...tab));
    let score = max;
    tab.unshift(tab.splice(max, 1)[0]);
    tab.reverse();
    let min = tab.indexOf(Math.min(...tab));
    score += min;
    console.log(score);

}

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let arr = inputs[1].trim().split(' ');
    let max = Math.max(...arr);
    let min = Math.min(...arr);
    let swaps = 0;
    if (arr[0] == max && arr[arr.length - 1] == min) {
        swaps = 0;
    }
    else {
        let minIndex = arr.lastIndexOf(String(min));

        for (let i = minIndex + 1; i < arr.length; i++) {
            if (+arr[minIndex] < +arr[i]) {
                let temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
                minIndex = i;
                swaps++;
            }
        }

        let maxIndex = arr.indexOf(String(max));
        for (let i = maxIndex - 1; i >= 0; i--) {
            if (+arr[maxIndex] > +arr[i]) {
                let temp = arr[i];
                arr[i] = arr[maxIndex];
                arr[maxIndex] = temp;
                maxIndex = i;
                swaps++;
            }
        }
    }

    return swaps.toString();
}

'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.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

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

function main() {
    let n = parseInt(readLine());
    let arr = readLine().split(' ').map(value => parseInt(value));
    let idxMax = arr.indexOf(Math.max(...arr));
    let min = Math.min(...arr);
    let idxMin = arr.indexOf(min);
    let arrIdxMin = [];
    while (idxMin != -1) {
        arrIdxMin.push(idxMin);
        idxMin = arr.indexOf(min, idxMin + 1);
    }
    idxMin = arrIdxMin[arrIdxMin.length - 1];
    if (idxMin < idxMax) {
        console.log(idxMax + n - idxMin - 2);
    } else {
        console.log(idxMax + n - idxMin - 1);
    }
}

var n=+readline();
var a=readline().split(' ').map(function(v){return+v;});
var min=a.indexOf( Math.min.apply(null, a) );
var max=a.indexOf( Math.max.apply(null, a) );
var ans=n-min-1+max;
if(max==min) print(0);
else print(min<max?ans-2:ans);

var n = +readline(), line = readline().split(" "), sorted = [], cmax, cmin, buf;
line.forEach(function(a){
	sorted.push(+a);
})
sorted.sort(function(a,b){return a-b});

cmin = line.lastIndexOf(sorted[0].toString(10));
cmax = line.indexOf(sorted[n-1].toString(10));

for(i = 1;  ; i++){
	if( cmax > 0 ){
		buf = line[cmax-1];
		line[cmax-1] = line[cmax];
		line[cmax] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
	}
	else if( cmin < n-1 ){
		buf = line[cmin+1];
		line[cmin+1] = line[cmin];
		line[cmin] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
	}
	if( (cmax == 0) && (cmin == n-1) ){
		write(i);
		break;
	}
}

var n = +readline(), line = readline().split(" "), sorted = [], cmax, cmin, buf;
line.forEach(function(a){
	sorted.push(+a);
})
sorted.sort(function(a,b){return a-b});

cmin = line.lastIndexOf(sorted[0].toString(10));
cmax = line.indexOf(sorted[n-1].toString(10));

for(i = 1;  ; i++){
	if( cmax > 0 ){
		buf = line[cmax-1];
		line[cmax-1] = line[cmax];
		line[cmax] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
		continue;
	}
	else if( cmin < n-1 ){
		buf = line[cmin+1];
		line[cmin+1] = line[cmin];
		line[cmin] = buf;
		cmin = line.lastIndexOf(sorted[0].toString(10));
		cmax = line.indexOf(sorted[n-1].toString(10));
	}
	if( (cmax == 0) && (cmin == n-1) ){
		write(i);
		break;
	}
}

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var temp = input[min_index];
input[min_index] = input[input.length - 1];
input[input.length - 1] = temp;
var max_index = input.indexOf(Math.max(...input));
var output = input.length-min_index+max_index;
print(output);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var max_index = input.indexOf(Math.max(...input));
print(2*input.length-min_index-max_index-1);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var max_index = input.indexOf(Math.max(...input));
print(max_index-1+input.length-min_index+1-1);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var temp = input[min_index];
input[min_index] = input[input.length - 1];
input[input.length - 1] = temp;
var max_index = input.indexOf(Math.max(...input));
var output = ((input.length-1)-min_index)+max_index;
print(output);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var max_index = input.indexOf(Math.max(...input));
print(2*input.lenth-min_index-max_index-1);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var max_index = input.indexOf(Math.max(...input));
print(max_index-1+input.length-1-min_index);

var w  = readline();
var input = readline().split(" ").map(x=>parseInt(x));
var min_index = input.lastIndexOf(Math.min(...input));
var max_index = input.indexOf(Math.max(...input));
print(max_index+input.length-min_index-1);

var n  = readline();//.split(" ");
var str  = readline().split(" ").map((x)=>+x);
var min = Math.min.apply(this, str); var max = Math.max.apply(this, str);
var MinIndex = str.lastIndexOf(min)+1; var MaxIndex = str.lastIndexOf(max)+1;

print(MaxIndex>MinIndex? MaxIndex-1+str.length-MinIndex-1:MaxIndex-1+str.length-MinIndex);

var n  = readline();//.split(" ");
var str  = "100 95 100 100 88".split(" ").map((x)=>+x);
var min = Math.min.apply(this, str); var max = Math.max.apply(this, str);
var MinIndex = str.lastIndexOf(min)+1; var MaxIndex = str.lastIndexOf(max)+1;

print(MaxIndex>MinIndex? MaxIndex-1+str.length-MinIndex-1:MaxIndex-1+str.length-MinIndex);

var n = readline();
var m = readline().split(" ");
var min = 0; var max = 0;
		for (var i=0; i<+n; i++){
			if (m[i]==Math.min.apply(this,m))//m[i+1]&&min<=m[i+1]){
				min = n-(i+1);
			else if (m[i]==Math.max.apply(this, m))
			max = (i+1)-1;
		}
	print(min+max-1);

var n = readline();
var m = readline().split(" ");
var temp = 0;
var res = 0;
	for (var j=0; j<+2; j++){
		for (var i=0; i<+n; i++){
			if (m[i]<m[i+1]){
				temp = m[i];
				m[i] = m[i+1];
				m[i+1] = temp;
				res++;
			}
		}
	}
	print(res);

var n  = readline();//.split(" ");
var str  = readline().split(" ").map((x)=>+x);
var min = Math.min.apply(this, str); var max = Math.max.apply(this, str);
var MinIndex = str.lastIndexOf(min)+1; var MaxIndex = str.lastIndexOf(max)+1;

print(min==+str[str.length-1]&&max==+str[0]? 0:
MaxIndex>MinIndex? MaxIndex-1+str.length-MinIndex-1:MaxIndex-1+str.length-MinIndex);

var n = readline();
var soliders = readline().split(" ");

var maxIndex = 0;
var minIndex = 0;
var swapTime = 0;

for(var i = 0; i < n; i++){
	maxIndex = (soliders[i] > soliders[maxIndex]) ? i : maxIndex;
	minIndex = (soliders[i] <= soliders[minIndex]) ? i : minIndex;
}

if(maxIndex > minIndex)
	swapTime = (parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex))-1);
else
	swapTime = parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex));
print(swapTime);

var n = readline();
var soliders = readline().split(" ");

var maxIndex = 0;
var minIndex = 0;
var swapTime = 0;

for(var i = 0; i < n; i++){
	maxIndex = (parseInt(soliders[i]) > parseInt(soliders[maxIndex])) ? i : maxIndex;
	minIndex = (parseInt(soliders[i]) <= parseInt(soliders[minIndex])) ? i : minIndex;
}
print(maxIndex+" "+minIndex);
if(maxIndex > minIndex)
	swapTime = (parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex))-1);
else
	swapTime = parseInt(maxIndex) + (parseInt(n)-1-parseInt(minIndex));
print(swapTime);

const readline = require('readline');

let inputs = [];

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

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    let arr = inputs[1].split(' ');
    let Pmax = arr.indexOf(Math.max(...arr).toString());
    let Pmin = 0;
    const shortestHeight = Math.min(...arr).toString();

    for (let i = arr.length; i > 0; i--) {
        if (arr[i] == shortestHeight) {
            Pmin = i;
        }
    }

    let minSeconds;
    Pmin = parseInt(Pmin)
    Pmax = parseInt(Pmax)

    if (Pmin < Pmax) {
        minSeconds = Pmax + (arr.length - Pmin) - 2;
    } else {
        minSeconds = Pmax + (arr.length - 1 - Pmin);
    }

    console.log(minSeconds);

})

const readline = require('readline');

let inputs = [];

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

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    let arr = inputs[1].split(' ');
    const Pmax = arr.indexOf(Math.max(...arr).toString());
    const shortestHeight = Math.min(...arr).toString();
    let Pmin;

    for (let i = arr.length; i > 0; i--) {
        if (arr[i] == shortestHeight) {
            Pmin = i;
        }
    }

    let minSeconds;
    if (parseInt(Pmin) < parseInt(Pmax)) {
        minSeconds = Pmax + (arr.length - Pmin) - 2
    } else {
        minSeconds = Pmax + (arr.length - 1 - Pmin);
    }

    console.log(minSeconds);

})

const readline = require('readline');

let inputs = [];

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

// Read Inputs
rl.on('line', lineInput => {
    inputs.push(lineInput)
})

rl.on('close', () => {

    let arr = inputs[1].split(' ');
    let Pmax = arr.indexOf(Math.max(...arr).toString());
    let Pmin = 0;
    const shortestHeight = Math.min(...arr).toString();

    for (let i = arr.length; i > 0; i--) {
        if (arr[i] == shortestHeight) {
            Pmin = i;

            let minSeconds;
            Pmin = parseInt(Pmin)
            Pmax = parseInt(Pmax)

            if (Pmin < Pmax) {
                minSeconds = Pmax + (arr.length - Pmin) - 2;
            } else {
                minSeconds = Pmax + (arr.length - 1 - Pmin);
            }

            return console.log(minSeconds);
        }
    }

})

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

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

  const arr = d.split(' ').map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  const idxMin = arr.lastIndexOf(min);
  const idxMax = arr.indexOf(max);

  ans += idxMax;

  if (arr.indexOf(min) > arr.indexOf(max)) {
    ans += Math.max(arr.length - idxMin - 1, 0);
  }
  else {
    ans += Math.max(arr.length - idxMin - 2, 0);
  }

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

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 arr = d.split(' ').map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  const ans = Math.max(arr.indexOf(max) - 1, 1) + arr.length - 1 - arr.lastIndexOf(min);

  // console.log(Math.max(arr.indexOf(max) - 1, 0), arr.length - 1 - arr.lastIndexOf(min));

  // let ans = 0;
  // let isSwap = true;

  // while (isSwap) {
  //   isSwap = false;

  //   for (let j = 0; j < arr.length - 1; j++) {
  //     if (arr[j] < arr[j + 1]) {
  //       const temp = arr[j];
  //       arr[j] = arr[j + 1];
  //       arr[j + 1] = temp;
  //       ans++;
  //       isSwap = true;
  //     }
  //   }
  // }

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

const readline = require('readline');

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

rl.on('line', input => {
  rl.on('line', input2 => {
    console.log(min(input2.split(' ').map(n => parseInt(n))));
    process.exit();
  });
});

const min = input => {
  const min = Math.min(...input);
  const max = Math.max(...input);
  let iMin = input.findIndex(e => e == min);
  let iMax = input.findIndex(e => e == max);
  let secs = 0;
  let temp = 0;

  while(input[input.length-1] !== min) {
    if(input[iMin+1] !== min) {
      temp = input[iMin+1];
      input[iMin+1] = input[iMin];
      input[iMin] = temp;
      secs++;
    }
    iMin++;
  }

  while(input[0] !== max) {
    if(input[iMax-1] !== max) {
      temp = input[iMax-1];
      input[iMax-1] = input[iMax];
      input[iMax] = temp;
      secs++;
    }
    iMax--;
  }

  return secs;
}

const readline = require('readline');

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

rl.on('line', input => {
  rl.on('line', input2 => {
    console.log(min(input2.split(' ').map(n => parseInt(n))));
    process.exit();
  });
});

const min = input => {
  const iMin = input.findIndex(e => e == Math.min(...input));
  const iMax = input.findIndex(e => e == Math.max(...input));

  return iMin > iMax ? input.length - 1 - iMin + iMax : input.length - 2 - iMin + iMax;
}

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function isPrime(x) {
	let s = Math.sqrt(x);
	let i = 2;
	while (i <= s) {
		if (x % i === 0) {
			return false;
		}
		i++;
	}
	return true;
}

function main() {
	let n = readLine() >> 0;
	let sol = readLine()
		.split(' ')
		.map(x => x >> 0);

	let sc = 0;

	let min = Math.min(...sol);
	let max = Math.max(...sol);
	let posMax = 0,
		posMin = 0;

	sol.forEach((x, i) => {
		if (x === min && i >= posMin) posMin = i;
		if (x === max) posMax = i;
	});

	sc = n - posMin - 1;
	if (posMax > posMin) sc += posMax - 1;
	else sc += posMax;

	console.log(sc);
}

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let arr = inputs[1].trim().split(' ');
    let max = Math.max(...arr);
    let min = Math.min(...arr);
    let swaps = 0;
    if (arr[0] == max && arr[arr.length - 1] == min) {
        swaps = 0;
    }
    else {
        let minIndex = arr.lastIndexOf(String(min));

        for (let i = minIndex + 1; i < arr.length; i++) {
            if (arr[minIndex] < arr[i]) {
                let temp = arr[i];
                arr[i] = arr[minIndex];
                arr[minIndex] = temp;
                minIndex = i;
                swaps++;
            }
        }

        let maxIndex = arr.indexOf(String(max));
        for (let i = maxIndex - 1; i >= 0; i--) {
            if (arr[maxIndex] > arr[i]) {
                let temp = arr[i];
                arr[i] = arr[maxIndex];
                arr[maxIndex] = temp;
                maxIndex = i;
                swaps++;
            }
        }
    }

    return swaps.toString();
}

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let arr = inputs[1].trim().split(' ');
    let swaps = 0;
    for (let i = 1; i < arr.length; i++) {
        let min = arr[i];
        let j = i - 1;
        while (j >= 0 && arr[j] < min) {
            arr[j + 1] = arr[j];
            j--;
            swaps++;
        }
        arr[j + 1] = min;
    }
    swaps = Math.abs(+inputs[0] - swaps);
    return swaps.toString();
}


There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes.The schedule on Monday is known for each group, i. e. time slots when group will have classes are known.Your task is to determine the minimum number of rooms needed to hold classes for all groups on Monday. Note that one room can hold at most one group class in a single time slot.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of groups.  Each of the following n lines contains a sequence consisting of 7 zeroes and ones — the schedule of classes on Monday for a group. If the symbol in a position equals to 1 then the group has class in the corresponding time slot. In the other case, the group has no class in the corresponding time slot.

Print minimum number of rooms needed to hold all groups classes on Monday.

NoteIn the first example one room is enough. It will be occupied in each of the seven time slot by the first group or by the second group.In the second example three rooms is enough, because in the seventh time slot all three groups have classes.

var n=parseInt(readline());
var max=0,count=0;
var ar=new Array(n);
var s="";
for(var i=0;i<n;i++){
	ar[i]=readline();
}
for(var y=0;y<7;y++){
	for(var i=0;i<n;i++){
		s=ar[i];
		count+=parseInt(s[y]);
	}
	if(count>max){max=count;}
	count=0;
}print(max);

n=+readline()
s=[]
for (var i=0;i<n;i++)
{
    s.push(readline())
}
var res=0;
for (var j=0;j<7;j++)
{
    var kol=0;
    for (var i=0;i<n;i++)
    {
        if (s[i][j]=='1')
        kol++
    }
    if (kol>res){res=kol;}
}
print(res)

// Classes to be taken on monday.
const classCount = 7;
// Getting problem data from codeforces.
var groupCount = parseInt(readline()),
  groupSchedules = [];
for(var j = 0;j<groupCount;++j){
  groupSchedules.push(readline());
}
// Computing required number of rooms.
var roomCount = 0,oneCounts = 0;
for(var j = 0; j<classCount;++j){
  for(var i = 0;i<groupCount;++i){
    groupSchedules[i][j] == '1'?
      oneCounts++:undefined;
  }
  roomCount = Math.max(roomCount,oneCounts);
    oneCounts = 0;
}
// Solution.
print(roomCount);

n=+readline()
s=[]
for (var i=0;i<n;i++)
{
    s.push(readline())
}
var res=0;
for (var j=0;j<7;j++)
{
    var kol=0;
    for (var i=0;i<n;i++)
    {
        kol+=s[i][j]
    }
    if (kol>res){res=kol;}
}
print(res)

// Classes to be taken on monday.
const classCount = 7;
// Getting problem data from codeforces.
var groupCount = parseInt(readline()),
  groupSchedules = [];
for(var j = 0;j<groupCount;++j){
  groupSchedules.push(readline());
}
// Computing required number of rooms.
var roomCount = -1,oneCounts = 0;
for(var j = 0; j<classCount;++j){
  for(var i = 0;i<groupCount;++i){
    groupSchedules[i][j] == '0'?
      oneCounts++:undefined;
  }
  roomCount = Math.max(roomCount,oneCounts);
    oneCounts = 0;
}
// Solution.
print(roomCount);