Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.

The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence.  The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105).

Print a single integer — the maximum number of points that Alex can earn.

NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points.

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

	this.sortComparator = function( left , right ) {
		return left - right ;
	} ;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , a , b , c ;
        res = 0 ;
        this.arr = this.arr.sort( this.sortComparator ) ;
        for( i = 0 ; i < this.n ; i++ ) {
        	this.brr[ this.arr[ i ] ]++ ;
        }
        for( i = 1 ; i <= 100000 ; i++ ) {
        	this.crr[ i + 2 ] = Math.max( this.crr[ i + 2 ] , this.crr[ i ] + this.brr[ i ] * i ) ;
        	this.crr[ i + 3 ] = Math.max( this.crr[ i + 3 ] , this.crr[ i ] + this.brr[ i ] * i ) ;
        	res = Math.max( res , this.crr[ i + 2 ] ) ;
        	res = Math.max( res , this.crr[ i + 3 ] ) ;
        }
        print( res );
    };

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

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

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

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

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

    this.init();
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    this.configureStreamsAndReadInput();
}

new CodeExecutioner();

/* TEST CASE
input
9
1 2 1 3 2 2 2 2 3
output
10

Input
5
3 3 4 5 4
Output
8
Answer
11

Input
5
4 2 3 2 5
Output
8
Answer
9

input
10
100000 100000 100000 100000 100000 100000 100000 100000 100000 100000
output
1000000

 */

function maximumPoints(a, m) {
	// a must be sorted by a.num in ascending order
	var maxOfK = new Array(m)

	maxOfK[0] = a[0].total;
	var maxValue = maxOfK[0];

	for (var k = 1; k < m; k++) {
		maxOfK[k] = a[k].total;

		if (a[k].num == a[k - 1].num + 1) {
			if (k > 1) {
				maxOfK[k] += maxOfK[k - 2];
			}
			maxOfK[k] = Math.max(maxOfK[k], maxOfK[k - 1]);
		} else {
			maxOfK[k] += maxOfK[k - 1];
		}

		if (maxOfK[k] > maxValue) {
			maxValue = maxOfK[k];
		}
	}

	return maxValue;
}

function main() {
	var n = parseInt(readline());
	var splitted = readline().split(' ');
	var freq = {};	//Map
	var i, j;
	var a = [];
	var num;
	for (i = 0; i < n; i++) {
		num = parseInt(splitted[i]);
		if (freq[num] == null) {
			a.push({num: num, total: 0});
			freq[num] = 1;
		} else {
			freq[num]++;
		}
	}
	var m = a.length;
	for (i = 0; i < m; i++) {
		a[i].total = a[i].num * freq[a[i].num];
	}
	a.sort(function(n1, n2) {return n1.num - n2.num;});	//ascending order
//FOR DEBUG:
//	for (i = 0; i < m; i++) {
//		print(a[i].num, a[i].total);
//	}
	var answer = maximumPoints(a, m);
	print(answer);
}

main();

/* TEST CASE
input
9
1 2 1 3 2 2 2 2 3
output
10

Input
5
3 3 4 5 4
Output
8
Answer
11

Input
5
4 2 3 2 5
Output
8
Answer
9

input
10
100000 100000 100000 100000 100000 100000 100000 100000 100000 100000
output
1000000

 */

function maximumPoints(a, m) {
	// a must be sorted by a.num in ascending order
	var maxOfK = new Array(m)

	maxOfK[0] = a[0].total;
	var maxValue = maxOfK[0];

	for (var k = 1; k < m; k++) {
		if (a[k].num == a[k - 1].num + 1) {
			maxOfK[k] = a[k].total;
			if (k > 1) {
				maxOfK[k] += maxOfK[k - 2];
			}
			maxOfK[k] = Math.max(maxOfK[k], maxOfK[k - 1]);
		} else {
			maxOfK[k] = a[k].total + maxOfK[k - 1];
		}

		if (maxOfK[k] > maxValue) {
			maxValue = maxOfK[k];
		}
	}

	return maxValue;
}

function main() {
	var n = parseInt(readline());
	var splitted = readline().split(' ');
	var freq = {};	//Map
	var i, j;
	var a = [];
	var num;
	for (i = 0; i < n; i++) {
		num = parseInt(splitted[i]);
		if (freq[num] == null) {
			a.push({num: num, total: 0});
			freq[num] = 1;
		} else {
			freq[num]++;
		}
	}
	var m = a.length;
	for (i = 0; i < m; i++) {
		a[i].total = a[i].num * freq[a[i].num];
	}
	a.sort(function(n1, n2) {return n1.num - n2.num;});	//ascending order
//FOR DEBUG:
//	for (i = 0; i < m; i++) {
//		print(a[i].num, a[i].total);
//	}
	var answer = maximumPoints(a, m);
	print(answer);
}

main();

var k = 100000;
var n = parseInt(readline());
var a = readline().split(" ").map(function(x) { return parseInt(x); });
var cnt = Array.apply(null, Array(k + 1)).map(Number.prototype.valueOf,0);
var dp = Array(k + 1);

for(var i = 0; i < n; i++)
  cnt[a[i]]++;

dp[0] = 0;
dp[1] = cnt[1];

for(var i = 2; i <= k; i++)
  dp[i] = Math.max(dp[i - 1], dp[i - 2] + cnt[i] * i)

print(dp[k])

var n = +readline();
var data = readline().split(' ');

var arr = new Array(100010).fill(0);
for (var i = 0; i < n; ++i) {
    ++arr[+data[i]];
}

var dp = new Array(n + 1);
dp[0] = 0;
dp[1] = arr[1];
for (var i = 2; i <= 100000; ++i) {
    dp[i] = Math.max(dp[i - 1], dp[i - 2] + (arr[i] * i));
}

write(dp[100000]);

var n = +readline();
var data = readline().split(' ');

var arr = new Array(100001).fill(0);
for (var i = 0; i < n; ++i) {
    ++arr[+data[i]];
}

var dp = [0, arr[1]];
for (var i = 2; i <= 100000; ++i) {
    dp.push(Math.max(dp[i - 1], dp[i - 2] + (arr[i] * i)));
}

write(dp[100000]);

n=Number(readline())
N=100000
A=readline().split(' ').map(Number)
    .reduce((a,c) => { a[c]++; return a }, (new Array(N+1)).fill(0))
FF={ 1:A[1] }

for (i=2; i<=N; ++i) {
    FF[i] = Math.max(A[i]*i + (FF[i-2]||0), (FF[i-1]||0))
}

print(FF[N])

var input = readline().split(' ').map(Number), n = input[0];
var a = readline().split(' ').map(Number);
var vals = [], res = [];
for (var i = -2; i <= 100000; i++) { vals[i] = 0; res[i] = 0; }
for (var i = 0; i < a.length; i++) vals[a[i]] += a[i];
for (var i = 1; i <= 100000; i++) {
    res[i] = Math.max(res[i-1], res[i-2] + vals[i], res[i-3] + vals[i]);
}
write(res[100000]);

// var _i = 0;
//
// function readline() {
//     _i ++;
//
//     switch (_i) {
//         case 1: return '9';
//         case 2: return '1 2 1 3 2 2 2 2 3';
//     }
// }
//
// function write(value) {
//     console.log(value);
// }

var n = parseInt(readline());

var maxA = 0;
var c = [];

readline().split(' ').forEach(function(element) {
    var a = parseInt(element);

    if (c[a] === undefined) {
        c[a] = 1;
    } else {
        c[a] ++;
    }

    maxA = Math.max(maxA, a);
});

var f = [];

f[0] = 0;
f[1] = c[1] || 0;

for (var i = 2; i <= maxA; i ++) {
    f[i] = Math.max(f[i-1], f[i-2] + (c[i] || 0)*i);
}

write(f[maxA]);

var n = readline(),
			a = readline(),
			array = a.replace(/\s{1,}/gi, ' ').split(/\s/),
			_array = {},
			_arrayKeySet = [],
			resultArray = {};

		array = array.map(function(value, index)	{
			if(!_array[value])	{
				_array[value] = 1;
			} else	{
				_array[value]++;
			}

			return parseInt(value);
		});

		_arrayKeySet = Object.keys(_array);

		for(var i=1; i<=_arrayKeySet[_arrayKeySet.length - 1]; i++)	{
			var preVal = !resultArray[i - 1] ? 0 : resultArray[i - 1],
				morePreVal = !resultArray[i - 2] ? 0 : resultArray[i - 2],
				currentVal = _array[i] * i;

			if(isNaN(currentVal))	currentVal = 0;

			resultArray[i] = Math.max(preVal, morePreVal + currentVal);
		}

		print(resultArray[i - 1]);

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

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

readLine.on('close', () => {
  const nums = input[1].split(' ').map(x => parseInt(x));
  nums.sort((a, b) => a - b);

  const newArr = [];
  const map = {};

  nums.forEach(x => {
    map[x] === undefined ? (map[x] = 1, newArr.push(x) ): map[x] += 1;
  });

  if (newArr.length === 1) {
    console.log(
      map[ newArr[0] ] * newArr[0]
    ); return;
  }
  if (newArr.length === 2) {
    console.log(
      Math.max( map[ newArr[0] ] * newArr[0], map[ newArr[1] ] * newArr[1] )
    ); return
  }

  const dp = [];
  dp[0] = map[newArr[0]] * newArr[0];
  dp[1] = Math.max(dp[0], map[newArr[1]] * newArr[1])

  if (newArr[0]+1 !== newArr[1]) {
    dp[1] += dp[0];
  }

  for (let i = 2; i < newArr.length; i += 1) {
    if (newArr[i-1]+1 !== newArr[i])
      dp[i] = Math.max(dp[i-2], dp[i-1]) + (map[newArr[i]] * newArr[i]);
    else
      dp[i] = Math.max(dp[i-2] + (map[newArr[i]] * newArr[i]), dp[i-1]);
  }

  console.log(dp.pop());
});

// https://codeforces.com/contest/455/problem/A
process.stdin.resume();
process.stdin.setEncoding("ascii");

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on("data", function(data) {
  input_stdin += data;
});

process.stdin.on("end", function() {
  input_stdin_array = input_stdin.split("\n");
  main();
});

function readLine() {
  return input_stdin_array[input_currentline++];
}

function unaryParseInt(val) {
  return parseInt(val);
}

function getFrequencies(arr) {
  return arr.reduce((freq, num) => {
    if (freq[num]) {
      freq[num] += 1;
    } else {
      freq[num] = 1;
    }
    return freq;
  }, {});
}

function getUptoArr(arr, freq) {
  const upto = [];
  const first = arr[0];
  const last = arr[arr.length - 1];
  upto[first] = first * freq[first];
  for (let i = first + 1; i <= last; i++) {
    upto[i] = freq[i]
      ? Math.max(i * freq[i] + (upto[i - 2] || 0), upto[i - 1])
      : upto[i - 1];
  }
  return upto;
}

function getFromArr(arr, freq) {
  const from = [];
  const first = arr[0];
  const last = arr[arr.length - 1];
  from[last] = last * freq[last];
  for (let i = last - 1; i >= first; i--) {
    from[i] = freq[i]
      ? Math.max(i * freq[i] + (from[i + 2] || 0), from[i + 1])
      : from[i + 1];
  }
  return from;
}

function solve(arr) {
  const freq = getFrequencies(arr);
  const unique = [...new Set(arr)].sort((a, b) => (a > b ? 1 : -1));
  const uptoX = getUptoArr(unique, freq);
  const fromX = getFromArr(unique, freq);

  let ans = 1;
  for (let i = 0; i < unique.length; i++) {
    const curr = unique[i];
    ans = Math.max(
      ans,
      curr * freq[curr] + (uptoX[curr - 2] || 0) + (fromX[curr + 2] || 0)
    );
  }

  return ans;
}

function main() {
  readLine();
  const arr = readLine()
    .split(" ")
    .map(unaryParseInt);

  var res = solve(arr);
  console.log(res);
}

function countUniqueElements(input,output,unique){
	for(var i = 0; i < input.length; i++){
		if(output[+input[i]] == undefined){
			output[+input[i]] = 1;
			unique.push(+input[i]);
		}
		else{
			output[+input[i]]++;
		}
	}
}

var n = +readline(), a = readline().split(" "),
cnt = [], unique = [];

countUniqueElements(a,cnt,unique);
unique.sort(function(x,y){return x-y});

var gain = [cnt[unique[0]]*unique[0]];

if(unique.length > 1){
	if(unique[1] == unique[0]+1){
		gain[1] = Math.max(gain[0],unique[1]*cnt[unique[1]]);
	}
	else{
		gain[1] = gain[0] + unique[1]*cnt[unique[1]];
	}
	for(var i = 2; i < unique.length; i++){
		if(unique[i] == unique[i-1]+1){
			gain[i] = Math.max(gain[i-1], gain[i-2] + unique[i]*cnt[unique[i]]);
		}
		else{
			gain[i] = gain[i-1] + unique[i]*cnt[unique[i]];
		}
	}
}

write(gain[unique.length-1]);

readline(); a = {}; readline().split(' ').forEach(i => a[i] = a[i] ? a[i] + 1: 1);
n = Math.max.apply(null, Object.keys(a)); r=0; t=0;
for (i = 1; i <= n; i++) r = a[i] ? Math.max(a[i] * i + t, t = r) : t = r;

write(r);

readline(); a = {}; readline().split(' ').map(Number).forEach(i => a[i] = a[i] ? a[i] + i: i);
n = Math.max.apply(null, Object.keys(a)); r=0; t=0;
for (i = 1; i <= n; i++) r = a[i] ? Math.max(a[i] + t, t = r) : t = r;

write(r);

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

var sum = [], res = [];

for(var i=-2; i<=100000; i++)
{
  sum[i] = 0;
  res[i] = 0;
}

for(var i=0; i<a.length; i++)
{
  sum[a[i]] += a[i];
}

for(var i=1; i<=100000; i++)
{
  res[i] = Math.max(res[i-1], res[i-2]+sum[i], res[i-3]+sum[i]);
}

print(res[100000]);

var ints = function() {
	return readline().split(' ').map(function(w) {
		return parseInt(w)
	})
}

readline()
var a = ints()

var numbers = [],
	max = 0
a.forEach(function(n) {
	if (numbers[n] == undefined)
		numbers[n] = 0
	numbers[n] += n
	if (max < n)
		max = n
})

var i = 0,
	j = 0,
	k = 0

while (max >= 0) {
	k = j
	j = i
	i = Math.max((numbers[max] || 0) + k, j)
	max --
}

print(i)

var ints = function() {
	return readline().split(' ').map(function(w) {
		return parseInt(w)
	})
}

readline()
var a = ints()

var numbers = [],
	max = 0
a.forEach(function(n) {
	if (numbers[n] == undefined)
		numbers[n] = 0
	numbers[n] += n
	if (max < n)
		max = n
})

var mem = []

mem[max + 1] = 0
mem[max + 2] = 0

while (max >= 0) {
	mem[max] = Math.max((numbers[max] || 0) + mem[max + 2], mem[max + 1])
	max --
}

print(mem[0])

print(function (n) {
	var m = {}, ret = {};
	readline().split(' ').forEach(function(e) { m[e] = m[e] ? m[e] + 1: 1; });

	for(var i = 1, _i = Math.max.apply(null, Object.keys(m)) + 1; i < _i ; i++)
		ret[i] = Math.max(ret[i - 1] || 0, (ret[i - 2] || 0) + (m[i] * i || 0));

	return ret[i - 1]
}(+readline()));

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

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

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

function main() {
	var n = parseInt(readline()),
		data = tokenizeIntegers(readline()),
		items = [], freq = {};
	for (var i = 0; i < n; ++i) {
		var item = data[i];
		if (freq[item] === undefined) {
			items.push(item);
			freq[item] = 0;
		}
		freq[item] += 1;
	}
	items.sort(function (a, b) {
		return a - b;
	});
	var numItems = items.length,
		gain = new Array(numItems);
	gain[0] = items[0] * freq[items[0]];
	if (numItems > 1) {
		if (items[0] == items[1]-1) {
			gain[1] = Math.max(gain[0], items[1] * freq[items[1]]);
		} else {
			gain[1] = gain[0] + items[1] * freq[items[1]];
		}
	}
	for (var i = 2; i < numItems; ++i) {
		if (items[i-1] == items[i]-1) {
			gain[i] = Math.max(gain[i-1],
					gain[i-2] + items[i] * freq[items[i]]);
		} else {
			gain[i] = gain[i-1] + items[i] * freq[items[i]];
		}
	}
	print(gain[numItems-1]);
}

main();

/* TEST CASE
input
2
1 2
output
2
input
3
1 2 3
output
4
input
9
1 2 1 3 2 2 2 2 3
output
10
 */
function main() {
	var n = parseInt(readline());
	var splitted = readline().split(' ');
	var freq = {};	//Map
	var i, j;
	var a = [];
	var num;
	for (i = 0; i < n; i++) {
		num = parseInt(splitted[i]);
		if (freq[num] == null) {
			a.push({num: num, total: 0});
			freq[num] = 1;
		} else {
			freq[num]++;
		}
	}
	for (i = 0; i < a.length; i++) {
		a[i].total = a[i].num * freq[a[i].num];
	}
	a.sort(function(n1, n2) {return n1.total - n2.total;});	//ascending order
	var answer = 0;

	while (a.length > 0) {
		var chosen = a.pop();
		if (freq[chosen.num] != null) {
			answer += chosen.total;
			freq[chosen.num - 1] = null;
			freq[chosen.num + 1] = null;
		}
	}

	print(answer);
}

main();

/* TEST CASE
input
9
1 2 1 3 2 2 2 2 3
output
10

Input
5
3 3 4 5 4
Output
8
Answer
11

Input
5
4 2 3 2 5
Output
8
Answer
9

 */

function maximumPoints_ITERATIVE(a, m) {
	// a must be sorted by a.num in ascending order
	var maxValue = 0;
	var maxOfK = new Array(m)

	maxOfK[0] = a[0].total;

	for (var k = 1; k < m; k++) {
		if (a[k].num == a[k - 1].num + 1) {
			maxOfK[k] = a[k].total;
			if (k > 1) {
				maxOfK[k] += maxOfK[k - 2];
			}
			maxOfK[k] = Math.max(maxOfK[k], maxOfK[k - 1]);
		} else {
			maxOfK[k] = a[k].total + maxOfK[k - 1];
		}

		if (maxOfK[k] > maxValue) {
			maxValue = maxOfK[k];
		}
	}

	return maxValue;
}

function main() {
	var n = parseInt(readline());
	var splitted = readline().split(' ');
	var freq = {};	//Map
	var i, j;
	var a = [];
	var num;
	for (i = 0; i < n; i++) {
		num = parseInt(splitted[i]);
		if (freq[num] == null) {
			a.push({num: num, total: 0});
			freq[num] = 1;
		} else {
			freq[num]++;
		}
	}
	var m = a.length;
	for (i = 0; i < m; i++) {
		a[i].total = a[i].num * freq[a[i].num];
	}
	a.sort(function(n1, n2) {return n1.num - n2.num;});	//ascending order
//FOR DEBUG:
//	for (i = 0; i < m; i++) {
//		print(a[i].num, a[i].total);
//	}
	var answer = maximumPoints_ITERATIVE(a, m);
	print(answer);
}

main();

/* TEST CASE
Input
5
3 3 4 5 4
Output
8
Answer
11

input
2
1 2
output
2
input
3
1 2 3
output
4
input
9
1 2 1 3 2 2 2 2 3
output
10
 */

function maximumPoints_ITERATIVE(a, m) {
	// a must be sorted by a.num in ascending order
	var maxValue = 0;
	var maxOfK = new Array(m)

	maxOfK[0] = a[0].total;

	for (var k = 1; k < m; k++) {
		if (a[k].num == a[k - 1].num + 1) {
			maxOfK[k] = a[k].total;
			if (k > 1) {
				maxOfK[k] += maxOfK[k - 2];
			}
		} else {
			maxOfK[k] = a[k].total + maxOfK[k - 1];
		}

		if (maxOfK[k] > maxValue) {
			maxValue = maxOfK[k];
		}
	}

	return maxValue;
}

function main() {
	var n = parseInt(readline());
	var splitted = readline().split(' ');
	var freq = {};	//Map
	var i, j;
	var a = [];
	var num;
	for (i = 0; i < n; i++) {
		num = parseInt(splitted[i]);
		if (freq[num] == null) {
			a.push({num: num, total: 0});
			freq[num] = 1;
		} else {
			freq[num]++;
		}
	}
	var m = a.length;
	for (i = 0; i < m; i++) {
		a[i].total = a[i].num * freq[a[i].num];
	}
	a.sort(function(n1, n2) {return n1.num - n2.num;});	//ascending order
//FOR DEBUG:
//	for (i = 0; i < m; i++) {
//		print(a[i].num, a[i].total);
//	}
	var answer = maximumPoints_ITERATIVE(a, m);
	print(answer);
}

main();

var n = parseInt(readline());
var a = readline().split(" ").map(function(x) { return parseInt(x); });
var cnt = Array.apply(null, Array(n + 1)).map(Number.prototype.valueOf,0);
var dp = Array(n + 1);

for(var i = 0; i < n; i++)
  cnt[a[i]]++;

dp[0] = 0;
dp[1] = cnt[1];

for(var i = 2; i <= n; i++)
  dp[i] = Math.max(dp[i - 1], dp[i - 2] + cnt[i] * i)

print(dp[n])

var n = +readline();
var data = readline().split(' ');

var arr = new Array(100010).fill(0);
for (var i = 0; i < n; ++i) {
    ++arr[+data[i]];
}

var dp = new Array(n + 1);
dp[0] = 0;
dp[1] = arr[1];
for (var i = 2; i <= n; ++i) {
    dp[i] = Math.max(dp[i - 1], dp[i - 2] + (arr[i] * i));
}

write(dp[n]);

n=Number(readline())
N=100000
A=readline().split(' ').map(Number)
    .reduce((a,c) => { a[c]++; return a }, (new Array(N+1)).fill(0))
FF={}
// const f = i => {
//     print(i)
//     if (i<N) {
//         FF[i] = (i in FF) ? FF[i] :
//             Math.max(A[i]*i+f(i+2), A[i+1]*(i+1) + f(i+3))
//         return FF[i]
//     } else return 0;

// }
for (i=N; i>=0; --i) {
    FF[i] = Math.max(A[i]*i+FF[i+2]||0, A[i+1]*(i+1) + FF[i+3]||0)
}

print(FF[0])

var input = readline().split(' ').map(Number), n = input[0];
var a = readline().split(' ').map(Number);
var vals = [], res = [];
for (var i = -2; i <= 10000; i++) { vals[i] = 0; res[i] = 0; }
for (var i = 0; i < a.length; i++) vals[a[i]] += a[i];
for (var i = 1; i <= 10000; i++) {
    res[i] = Math.max(res[i-1], res[i-2] + vals[i], res[i-3] + vals[i]);
}
write(res[10000]);

var n = parseInt(readline());

var a = readline().split(' ').map(function (currentValue) {
    return parseInt(currentValue);
});

var c = [];
var u = [];

for (var i = 0; i < n; i ++) {
    if (c[a[i]] === undefined) {
        c[a[i]] = 1;
    } else {
        c[a[i]] ++;
    }
}

a.sort(function (x, y) {
    return c[y]*y - c[x]*x;
});

var sum = 0;

for (var i = 0; i < n; i ++) {
    if (u[a[i]] === undefined) {
        sum += a[i];
    }
    u[a[i]-1] = true;
    u[a[i]+1] = true;
}

write(sum);

// var _i = 0;
//
// function readline() {
//     _i ++;
//
//     switch (_i) {
//         case 1: return '5';
//         case 2: return '3 3 4 4 5';
//     }
// }
//
// function write(value) {
//     console.log(value);
// }

function getSum(a, n) {
    var c = [];
    var u = [];

    var sum = 0;

    for (var i = 0; i < n; i ++) {
        if (u[a[i]] === undefined) {
            sum += a[i];
            u[a[i]-1] = true;
            u[a[i]+1] = true;
        }
    }

    return sum;
}

var n = parseInt(readline());

var a = readline().split(' ').map(function (currentValue) {
    return parseInt(currentValue);
});

var c = [];

for (var i = 0; i < n; i ++) {
    if (c[a[i]] === undefined) {
        c[a[i]] = 1;
    } else {
        c[a[i]] ++;
    }
}

a.sort(function(x, y) {
    return y*c[y] - x*c[x];
});

var sum1 = getSum(a, n);

a.sort(function(x, y) {
    return y - x;
});

var sum2 = getSum(a, n);

write(Math.max(sum1, sum2));

// var _i = 0;
//
// function readline() {
//     _i ++;
//
//     switch (_i) {
//         case 1: return '9';
//         case 2: return '1 2 1 3 2 2 2 2 3';
//     }
// }
//
// function write(value) {
//     console.log(value);
// }

var n = parseInt(readline());

var a = readline().split(' ').map(function (currentValue) {
    return parseInt(currentValue);
});

var c = [];
var u = [];

for (var i = 0; i < n; i ++) {
    if (c[a[i]] === undefined) {
        c[a[i]] = 1;
    } else {
        c[a[i]] ++;
    }
}

a.sort(function (x, y) {
    return c[y]*y - c[x]*x;
});

var sum = 0;

for (var i = 0; i < n; i ++) {
    if (u[a[i]] === undefined) {
        sum += a[i];
        u[a[i]-1] = true;
        u[a[i]+1] = true;
    }
}

write(sum);

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

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

readLine.on('close', () => {
  const nums = input[1].split(' ').map(x => parseInt(x));
  nums.sort((a, b) => a - b);

  const newArr = [];
  const map = {};

  nums.forEach(x => {
    map[x] === undefined ? (map[x] = 1, newArr.push(x) ): map[x] += 1;
  });

  if (newArr.length === 1) {
    console.log(
      map[ newArr[0] ] * newArr[0]
    ); return;
  }
  if (newArr.length === 2) {
    console.log(
      Math.max( map[ newArr[0] ] * newArr[0], map[ newArr[1] ] * newArr[1] )
    ); return
  }

  const dp = [];
  dp[0] = map[newArr[0]] * newArr[0];
  dp[1] = Math.max(dp[0], map[newArr[1]] * newArr[1])
  for (let i = 2; i < newArr.length; i += 1) {
    dp[i] = Math.max(dp[i-2]+ (map[newArr[i]] * newArr[i]), dp[i-1]);
  }

  console.log(dp.pop());
});

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

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

readLine.on('close', () => {
  const nums = input[1].split(' ').map(x => parseInt(x));
  nums.sort((a, b) => a - b);

  const newArr = [];
  const map = {};

  nums.forEach(x => {
    map[x] === undefined ? (map[x] = 1, newArr.push(x) ): map[x] += 1;
  });

  if (newArr.length === 1) {
    console.log(
      map[ newArr[0] ] * newArr[0]
    ); return;
  }
  if (newArr.length === 2) {
    console.log(
      Math.max( map[ newArr[0] ] * newArr[0], map[ newArr[1] ] * newArr[1] )
    ); return
  }

  let answ = 0;
  for (let i = 0; i < newArr.length - 2; i += 1) {

    answ += Math.max(
      map[ newArr[i] ] * newArr[i] + map[ newArr[i+2] ] * newArr[i+2],
      map[ newArr[i + 1] ] * newArr[i + 1]
    );

    if (map[ newArr[i] ] * newArr[i] >  map[ newArr[i + 1] ] * newArr[i + 1]) {
      i += 1; continue;
    } else {
       i += 2; continue;
    }
  }

  console.log(answ);

});

process.stdin.resume();
process.stdin.setEncoding("ascii");

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on("data", function(data) {
  input_stdin += data;
});

process.stdin.on("end", function() {
  input_stdin_array = input_stdin.split("\n");
  main();
});

function readLine() {
  return input_stdin_array[input_currentline++];
}

function unaryParseInt(val) {
  return parseInt(val);
}

function getFrequencies(arr) {
  return arr.reduce((freq, num) => {
    if (freq[num]) {
      freq[num] += 1;
    } else {
      freq[num] = 1;
    }
    return freq;
  }, {});
}

function getUptoArr(arr, freq) {
  const upto = [];
  const first = arr[0];
  const last = arr[arr.length - 1];
  upto[first] = first * freq[first];
  for (let i = first + 1; i <= last; i++) {
    upto[i] = freq[i]
      ? Math.max(i * freq[i] + (upto[i - 2] || 0), upto[i - 1])
      : upto[i - 1];
  }
  return upto;
}

function getFromArr(arr, freq) {
  const from = [];
  const first = arr[0];
  const last = arr[arr.length - 1];
  from[last] = last * freq[last];
  for (let i = last - 1; i >= first; i--) {
    from[i] = freq[i]
      ? Math.max(arr[i] * freq[arr[i]] + (from[i + 2] || 0), from[i + 1])
      : from[i + 1];
  }
  return from;
}

function solve(arr) {
  const freq = getFrequencies(arr);
  const unique = [...new Set(arr)].sort((a, b) => (a > b ? 1 : -1));
  const uptoX = getUptoArr(unique, freq);
  const fromX = getFromArr(unique, freq);

  let ans = 1;
  for (let i = 0; i < unique.length; i++) {
    const curr = unique[i];
    ans = Math.max(
      ans,
      curr * freq[curr] + (uptoX[curr - 2] || 0) + (fromX[curr + 2] || 0)
    );
  }

  return ans;
}

function main() {
  readLine();
  const arr = readLine()
    .split(" ")
    .map(unaryParseInt);

  var res = solve(arr);
  console.log(res);
}

process.stdin.resume();
process.stdin.setEncoding("ascii");

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on("data", function(data) {
  input_stdin += data;
});

process.stdin.on("end", function() {
  input_stdin_array = input_stdin.split("\n");
  main();
});

function readLine() {
  return input_stdin_array[input_currentline++];
}

function unaryParseInt(val) {
  return parseInt(val);
}

function getFrequencies(arr) {
  return arr.reduce((freq, num) => {
    if (freq[num]) {
      freq[num] += 1;
    } else {
      freq[num] = 1;
    }
    return freq;
  }, {});
}

function getUptoArr(arr, freq) {
  const upto = [];
  upto[0] = arr[0] * freq[arr[0]];
  for (let i = 1; i < arr.length; i++) {
    upto[i] = Math.max(arr[i] * freq[arr[i]] + (upto[i - 2] || 0), upto[i - 1]);
  }
  return upto;
}

function getFromArr(arr, freq) {
  const from = [];
  const n = arr.length;
  from[n - 1] = arr[n - 1] * freq[arr[n - 1]];
  for (let i = n - 1; i >= 0; i--) {
    from[i] = Math.max(arr[i] * freq[arr[i]] + (from[i + 2] || 0), from[i + 1]);
  }
  return from;
}

function solve(arr) {
  const freq = getFrequencies(arr);
  const unique = [...new Set(arr)];
  const uptoX = getUptoArr(unique, freq);
  const fromX = getFromArr(unique, freq);

  let ans = 1;
  for (let i = 0; i < unique.length; i++) {
    const curr = unique[i];
    ans = Math.max(
      ans,
      curr * freq[curr] + (uptoX[i - 2] || 0) + (fromX[i + 2] || 0)
    );
  }

  return ans;
}

function main() {
  readLine();
  const arr = readLine()
    .split(" ")
    .map(unaryParseInt);

  var res = solve(arr);
  console.log(res);
}

process.stdin.resume();
process.stdin.setEncoding("ascii");

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on("data", function(data) {
  input_stdin += data;
});

process.stdin.on("end", function() {
  input_stdin_array = input_stdin.split("\n");
  main();
});

function readLine() {
  return input_stdin_array[input_currentline++];
}

function unaryParseInt(val) {
  return parseInt(val);
}

function getFrequencies(arr) {
  return arr.reduce((freq, num) => {
    if (freq[num]) {
      freq[num] += 1;
    } else {
      freq[num] = 1;
    }
    return freq;
  }, {});
}

function getUptoArr(arr, freq) {
  const upto = [];
  upto[0] = arr[0] * freq[arr[0]];
  for (let i = 1; i < arr.length; i++) {
    upto[i] = Math.max(arr[i] * freq[arr[i]] + (upto[i - 2] || 0), upto[i - 1]);
  }
  return upto;
}

function getFromArr(arr, freq) {
  const from = [];
  const n = arr.length;
  from[n - 1] = arr[n - 1] * freq[arr[n - 1]];
  for (let i = n - 1; i >= 0; i--) {
    from[i] = Math.max(arr[i] * freq[arr[i]] + (from[i + 2] || 0), from[i + 1]);
  }
  return from;
}

function solve(arr) {
  const freq = getFrequencies(arr);
  const unique = [...new Set(arr)].sort((a, b) => a > b ? 1 : -1);
  const uptoX = getUptoArr(unique, freq);
  const fromX = getFromArr(unique, freq);

  let ans = 1;
  for (let i = 0; i < unique.length; i++) {
    const curr = unique[i];
    ans = Math.max(
      ans,
      curr * freq[curr] + (uptoX[i - 2] || 0) + (fromX[i + 2] || 0)
    );
  }

  return ans;
}

function main() {
  readLine();
  const arr = readLine()
    .split(" ")
    .map(unaryParseInt);

  var res = solve(arr);
  console.log(res);
}

readline(); a = {}; readline().split(' ').forEach(i => a[i] = a[i] ? a[i] + 1: i);
n = Math.max.apply(null, Object.keys(a)); r=0; t=0;
for (i = 1; i <= n; i++) r = a[i] ? Math.max(a[i] * i + t, t = r) : t = r;

write(r);

;(function () {

	print(function (n) {
		var m = {}, sum = 0;
		readline().split(' ').forEach(function (e) { m[e] = m[e] ? m[e] + 1 : 1; });

		var k = Object.keys(m).map(Number);
		for (var i = 0, _i = k.length; i < _i; i++) {
			var t = k[i];
			if (k.indexOf(t - 1) === -1 && k.indexOf(t + 1) === -1) {
				sum += m[k[i]] * k[i];
				delete m[k[i]];
			}
		}

		k = Object.keys(m).map(Number).sort(function (a, b) { return a - b; });
		for (var i = 0, _I = -1, I_ = -1, _i = k.length; i < _i; i++) {
			var t = k[i];
			if (k.indexOf(t - 1) === -1) _I = i;
			if (k.indexOf(t + 1) === -1) I_ = i;
			if (_I !== -1 && I_ !== -1) {
				for (var j = _I, s = [0, 0]; j <= I_; j++)
					s[j%2] += m[k[j]] * k[j];
				sum += Math.max.apply(null, s);
				_I = I_ = -1;
			}
		}

		return sum;
	}(+readline()));

}).call(this);

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

	this.sortComparator = function( left , right ) {
		return left - right ;
	} ;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , a , b , c ;
        res = 0 ;
        this.arr = this.arr.sort( this.sortComparator ) ;
        for( i = 0 ; i < this.n ; i++ ) {
        	this.brr[ this.arr[ i ] ]++ ;
        }
        for( i = 1 ; i <= 100000 ; i++ ) {
        	this.crr[ i + 2 ] = Math.max( this.crr[ i + 2 ] , this.crr[ i ] + this.brr[ i ] * i ) ;
        	res = Math.max( res , this.crr[ i + 2 ] ) ;
        }
        print( res );
    };

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

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

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

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

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

    this.init();
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    this.configureStreamsAndReadInput();
}

new CodeExecutioner();


You are given a positive integer $$$m$$$ and two integer sequence: $$$a=[a_1, a_2, \ldots, a_n]$$$ and $$$b=[b_1, b_2, \ldots, b_n]$$$. Both of these sequence have a length $$$n$$$.Permutation is a sequence of $$$n$$$ different positive integers from $$$1$$$ to $$$n$$$. For example, these sequences are permutations: $$$[1]$$$, $$$[1,2]$$$, $$$[2,1]$$$, $$$[6,7,3,4,1,2,5]$$$. These are not: $$$[0]$$$, $$$[1,1]$$$, $$$[2,3]$$$.You need to find the non-negative integer $$$x$$$, and increase all elements of $$$a_i$$$ by $$$x$$$, modulo $$$m$$$ (i.e. you want to change $$$a_i$$$ to $$$(a_i + x) \bmod m$$$), so it would be possible to rearrange elements of $$$a$$$ to make it equal $$$b$$$, among them you need to find the smallest possible $$$x$$$.In other words, you need to find the smallest non-negative integer $$$x$$$, for which it is possible to find some permutation $$$p=[p_1, p_2, \ldots, p_n]$$$, such that for all $$$1 \leq i \leq n$$$, $$$(a_i + x) \bmod m = b_{p_i}$$$, where $$$y \bmod m$$$ — remainder of division of $$$y$$$ by $$$m$$$.For example, if $$$m=3$$$, $$$a = [0, 0, 2, 1], b = [2, 0, 1, 1]$$$, you can choose $$$x=1$$$, and $$$a$$$ will be equal to $$$[1, 1, 0, 2]$$$ and you can rearrange it to make it equal $$$[2, 0, 1, 1]$$$, which is equal to $$$b$$$.

The first line contains two integers $$$n,m$$$ ($$$1 \leq n \leq 2000, 1 \leq m \leq 10^9$$$): number of elemens in arrays and $$$m$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < m$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \leq b_i < m$$$). It is guaranteed that there exists some non-negative integer $$$x$$$, such that it would be possible to find some permutation $$$p_1, p_2, \ldots, p_n$$$ such that $$$(a_i + x) \bmod m = b_{p_i}$$$.

Print one integer, the smallest non-negative integer $$$x$$$, such that it would be possible to find some permutation $$$p_1, p_2, \ldots, p_n$$$ such that $$$(a_i + x) \bmod m = b_{p_i}$$$ for all $$$1 \leq i \leq n$$$.

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const [n, m] = arr[0].split(' ').map(a => parseInt(a))
  const a = arr[1].split(' ').map(a => parseInt(a))
  const b = arr[2].split(' ').map(a => parseInt(a))
  const ans = []

  sort(a)
  sort(b)

  for(let i = 0; i < n; i++) {
    let flag = true
    let x = (b[i] - a[0] + m) % m
    for(let j = 0; j < n; j++) {
      if((a[j] + x) % m == b[(i + j) % n]) continue
      else flag = false
    }
    if(flag) ans.push(x)
  }

  sort(ans)
  wr(ans[0])

})

function wr(...x) {
  console.log(...x)
}

function max(...x) {
  return Math.max(...x)
}

function min(...x) {
  return Math.min(...x)
}

function mod(a, m) {
  let x = a % m
  if(x >= 0 )  return x
  else return m + x
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const [n, m] = arr[0].split(' ').map(a => parseInt(a))
  const a = arr[1].split(' ').map(a => parseInt(a))
  const b = arr[2].split(' ').map(a => parseInt(a))

  let s1 = 0, s2 = 0

  for(let i = 0; i < n; i++) {
    s1 += a[i]
    s2 += b[i]
  }

  let d = mod(s2 - s1, m)
  let x

  // wr(m, d, s1, s2)
  for(let i = 0; ; i++) {
    // wr(i)
    if((m * i + d) % n == 0) {
      x = i
      break
    }
  }
  wr(x % m)
})

function wr(...x) {
  console.log(...x)
}

function max(...x) {
  return Math.max(...x)
}

function min(...x) {
  return Math.min(...x)
}

function mod(a, m) {
  let x = a % m
  if(x >= 0)  return x
  else return m - x
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const [n, m] = arr[0].split(' ').map(a => parseInt(a))
  const a = arr[1].split(' ').map(a => parseInt(a))
  const b = arr[2].split(' ').map(a => parseInt(a))

  let s1 = 0, s2 = 0

  for(let i = 0; i < n; i++) {
    s1 += a[i]
    s2 += b[i]
  }

  let d = mod(s2 - s1, m)
  let x

  // wr(m, d, s1, s2)
  for(let i = 0; ; i++) {
    // wr(i)
    if((m * i + d) % n == 0) {
      x = i
      break
    }
  }
  wr(x % m)
})

function wr(...x) {
  console.log(...x)
}

function max(...x) {
  return Math.max(...x)
}

function min(...x) {
  return Math.min(...x)
}

function mod(a, m) {
  let x = a % m
  if(x >= 0 )  return x
  else return m + x
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const [n, m] = arr[0].split(' ').map(a => parseInt(a))
  const a = arr[1].split(' ').map(a => parseInt(a))
  const b = arr[2].split(' ').map(a => parseInt(a))

  let s1 = 0, s2 = 0

  for(let i = 0; i < n; i++) {
    s1 += a[i]
    s2 += b[i]
  }

  let d = mod(s2 - s1, m)
  let x

  // wr(m, d, s1, s2)
  for(let i = 0; ; i++) {
    // wr(i)
    if((m * i + d) % n == 0) {
      x = (m * i + d) / n
      break
    }
  }
  wr(x % m)
})

function wr(...x) {
  console.log(...x)
}

function max(...x) {
  return Math.max(...x)
}

function min(...x) {
  return Math.min(...x)
}

function mod(a, m) {
  let x = a % m
  if(x >= 0 )  return x
  else return m + x
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  const [n, m] = arr[0].split(' ').map(a => parseInt(a))
  const a = arr[1].split(' ').map(a => parseInt(a))
  const b = arr[2].split(' ').map(a => parseInt(a))

  let s1 = 0, s2 = 0

  for(let i = 0; i < n; i++) {
    s1 += a[i]
    s2 += b[i]
  }

  let d = mod(s2 - s1, m)
  let x

  // wr(m, d, s1, s2)
  for(let i = 0; ; i++) {
    // wr(i)
    if((m * i + d) % n == 0) {
      x = (m * i + d) % n
      break
    }
  }
  wr(x % m)
})

function wr(...x) {
  console.log(...x)
}

function max(...x) {
  return Math.max(...x)
}

function min(...x) {
  return Math.min(...x)
}

function mod(a, m) {
  let x = a % m
  if(x >= 0 )  return x
  else return m + x
}


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. You have to choose a positive integer $$$d$$$ and paint all elements into two colors. All elements which are divisible by $$$d$$$ will be painted red, and all other elements will be painted blue.The coloring is called beautiful if there are no pairs of adjacent elements with the same color in the array. Your task is to find any value of $$$d$$$ which yields a beautiful coloring, or report that it is impossible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of elements of the array. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{18}$$$).

For each testcase print a single integer. If there is no such value of $$$d$$$ that yields a beautiful coloring, print $$$0$$$. Otherwise, print any suitable value of $$$d$$$ ($$$1 \le d \le 10^{18}$$$).

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

  main(lines);
});

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

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

function solve(N, arr) {
  let evenGCD = arr[0];
  let oddGCD = arr[1];
  let result1, result2;

  for (let i = 2; i < N; ++i) {
    if (i % 2 === 0) {
      evenGCD = gcd(arr[i], evenGCD);
    } else {
      oddGCD = gcd(arr[i], oddGCD);
    }
  }

  result1 = evenGCD;

  for (let i = 1; i < N; ++i) {
    if ((arr[i] % result1 === 0n) === (arr[i - 1] % result1 === 0n)) {
      result1 = 0n;
      break;
    }
  }

  result2 = oddGCD;

  for (let i = 1; i < N; ++i) {
    if ((arr[i] % result2 === 0n) === (arr[i - 1] % result2 === 0n)) {
      result2 = 0n;
      break;
    }
  }

  if (result1 === 0n && result2 === 0n) {
    console.log(0);
  } else if (result1 !== 0n) {
    console.log(result1.toString());
  } else {
    console.log(result2.toString());
  }
}

function gcd(a, b) {
  return (b === 0n ? a : gcd(b, a % b));
}

const solve = (n,arr)=>{
    const gcd = (a,b)=>b===0n ? a : gcd(b,a%b);
     let gcD = [arr[0],arr[1]];
     for(let i=0;i<n;i++){
          gcD[i%2] = gcd(gcD[i%2],arr[i]);
     }
     for(let i=0;i<2;i++){
          let res = -1n,flag = 1n;
          if(gcD[i]!==1n){
          for(let j=0;j<arr.length;j++){
               let t;
               if(arr[j]%gcD[i]) t=0n;
               else t = 1n;
               if(res===t){
                    flag = 0n;
                    break;
               };
               res = t;
          }
          if(flag===1n) return gcD[i]+"";
          }
     }
     return 0;
}

function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>BigInt(cur));
       console.log(solve(n,arr));
  }
}
main();

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 => BigInt(x));

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

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

		const gcd = [a[0], a[1]];
		for (let i = 0; i < n; i++)
			gcd[i%2] = calgcd(gcd[i%2], a[i]);

		let ans = 0n;
		for (let k = 0; !ans && k<2; k++) {
			let d = gcd[k], ok = true;
			for (let i = 0; ok && i < n; i++) {
				ok = a[i]%d == 0n;

				if (i&1) ok = !ok;
				if (k) ok = !ok;
			}
			ans = ok ? d : 0n;
		}

		console.log(ans.toString());
	}
}

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

  main(lines);
});

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

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

function solve(N, arr) {
  let evenGCD = arr[0];
  let oddGCD = arr[1];
  let greaterGCD;

  for (let i = 2; i < N; ++i) {
    if (i % 2 === 0) {
      evenGCD = gcd(arr[i], evenGCD);
    } else {
      oddGCD = gcd(arr[i], oddGCD);
    }
  }

  greaterGCD = evenGCD > oddGCD ? evenGCD : oddGCD;

  for (let i = 1; i < N; ++i) {
    if ((arr[i] % greaterGCD === 0n) === (arr[i - 1] % greaterGCD === 0n)) {
      console.log(0);
      return;
    }
  }

  console.log(greaterGCD.toString());
}

function gcd(a, b) {
  return (b === 0n ? a : gcd(b, a % b));
}

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

  main(lines);
});

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

  while (T--) {
    k++;
    N = Number(lines[index++]);
    arr = lines[index++].split(' ').map(BigInt);
    solve(N, arr);
    if (k === 20 && arr.length !== 2) {
      console.log('hello');
      console.log(arr);
      console.log('hello');
    }
  }
}

function solve(N, arr) {
  let result = BigInt(0);

  for (let i = 0; i < N; ++i) {
    result = arr[i];

    for (let j = 1; j < N; ++j) {
      if ((arr[j] % result === 0n) === (arr[j - 1] % result === 0n)) {
        result = 0n;
        break;
      }
    }

    if (result !== 0n) {
      break;
    }
  }

  console.log(result.toString());
}

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

  main(lines);
});

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

  while (T--) {
    k++;
    N = Number(lines[index++]);
    arr = lines[index++].split(' ').map(BigInt);
    solve(N, arr);
    if (k === 20) {
      console.log('hello');
      console.log(arr);
      console.log('hello');
    }
  }
}

function solve(N, arr) {
  let result = BigInt(0);

  for (let i = 0; i < N; ++i) {
    result = arr[i];

    for (let j = 1; j < N; ++j) {
      if ((arr[j] % result === 0n) === (arr[j - 1] % result === 0n)) {
        result = 0n;
        break;
      }
    }

    if (result !== 0n) {
      break;
    }
  }

  console.log(result.toString());
}

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

  main(lines);
});

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

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

function solve(N, arr) {
  let result = BigInt(0);

  for (let i = 0; i < N; ++i) {
    result = arr[i];

    for (let j = 1; j < N; ++j) {
      if ((arr[j] % result === 0n) === (arr[j - 1] % result === 0n)) {
        result = 0n;
        break;
      }
    }

    if (result !== 0n) {
      break;
    }
  }

  console.log(result.toString());
}

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

  main(lines);
});

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

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

function solve(N, arr) {
  let result = 0;

  for (let i = 0; i < N; ++i) {
    result = arr[i];

    for (let j = 1; j < N; ++j) {
      if ((arr[j] % result === 0) === (arr[j - 1] % result === 0)) {
        result = 0;
        break;
      }
    }

    if (result !== 0) {
      break;
    }
  }

  console.log(result);
}

const solve = (n,arr)=>{
     const gcd = (a,b)=>b===0n ? a : gcd(b,a%b);
     let first = [],second = [],k = false,gcD=[];
     for(let i=0;i<arr.length;i++){
          if(!k) first.push(arr[i]);
          else second.push(arr[i]);
          k=!k;
     }
     first.sort((a,b)=>parseInt(a-b));
     second.sort((a,b)=>parseInt(a-b));
     gcD[0] = first.length>1 ? gcd(first[0],first[1]) : first[0];
     gcD[1] = second.length>1 ? gcd(second[0],second[1]) : second[0];
     for(let i=0;i<2;i++){
          let res = -1n,flag = 1n;
          if(gcD[i]!==1n){
          for(let j=0;j<arr.length;j++){
               let t;
               if(arr[j]%gcD[i]) t=0n;
               else t = 1n;
               if(res===t){
                    flag = 0n;
                    break;
               };
               res = t;
          }
          if(flag===1n) return gcD[i]+"";
          }
     }
     return 0;
}

function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>BigInt(cur));
       console.log(solve(n,arr));
  }
}
main();

const solve = (n,arr)=>{
     const gcd = (a,b)=>b===0n ? a : gcd(b,a%b);
     let first = [],second = [],k = false,gcD=[];
     for(let i=0;i<arr.length;i++){
          if(!k) first.push(arr[i]);
          else second.push(arr[i]);
          k=!k;
     }
     first.sort((a,b)=>parseInt(a-b));
     second.sort((a,b)=>parseInt(a-b));
     gcD[0] = first.length>1 ? gcd(first[0],first[1]) : first[0];
     gcD[1] = second.lenght>1 ? gcd(second[0],second[1]) : second[0];
     for(let i=0;i<2;i++){
          let res = -1n,flag = 1n;
          if(gcD[i]!==1n){
          for(let j=0;j<arr.length;j++){
               let t;
               if(arr[j]%gcD[i]) t=0n;
               else t = 1n;
               if(res===t){
                    flag = 0n;
                    break;
               };
               res = t;
          }
          if(flag===1n) return gcD[i]+"";
          }
     }
     return 0;
}

function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>BigInt(cur));
       console.log(solve(n,arr));
  }
}
main();

const solve = (n,arr)=>{
    const gcd = (a,b)=>b===0 ? a : gcd(b,a%b);
     let first = [],second = [],k = false,gcD=[];
     for(let i=0;i<arr.length;i++){
          if(!k) first.push(arr[i]);
          else second.push(arr[i]);
          k=!k;
     }
     first.sort((a,b)=>a-b);
     second.sort((a,b)=>a-b);
     gcD[0] = first.length>1 ? gcd(first[0],first[1]) : first[0];
     gcD[1] = second.length>1 ? gcd(second[0],second[1]) : second[0];
     for(let i=0;i<2;i++){
          let res = -1,flag = 1;
          if(gcD[i]!==1){
          for(let j=0;j<arr.length;j++){
               let t;
               if(arr[j]%gcD[i]) t=0;
               else t = 1;
               if(res===t){
                    flag = 0;
                    break;
               }
               res = t;
          }
          if(flag===1) return gcD[i];
          }
     }
     return 0;
}

function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(n,arr));
  }
}
main();

const solve = (n,arr)=>{
    const gcd = (a,b)=>b===0 ? a : gcd(b,a%b);
     let first = [],second = [],k = false,gcD=[];
     for(let i=0;i<arr.length;i++){
          if(!k) first.push(arr[i]);
          else second.push(arr[i]);
          k=!k;
     }
     first.sort((a,b)=>a-b);
     second.sort((a,b)=>a-b);
     gcD[0] = first.length>1 ? gcd(first[0],first[1]) : first[0];
     gcD[1] = second.lenght>1 ? gcd(second[0],second[1]) : second[0];
     for(let i=0;i<2;i++){
          let res = -1,flag = 1;
          if(gcD[i]!==1){
          for(let j=0;j<arr.length;j++){
               let t;
               if(arr[j]%gcD[i]) t=0;
               else t = 1;
               if(res===t){
                    flag = 0;
                    break;
               }
               res = t;
          }
          if(flag===1) return gcD[i];
          }
     }
     return 0;
}

function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(n,arr));
  }
}
main();

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 => BigInt(x));

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

		let ans = 0;
		for (let k = 0; !ans && k < 2; k++) {
			let d = a[k], ok = true;
			for (let i = 0; ok && i < n; i++) {
				ok = a[i] % d == 0n;

				if (i&1) ok = !ok;
				if (k) ok = !ok;
			}
			ans = ok ? d : 0;
		}

		console.log(ans.toString());
	}
}

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 => BigInt(x));

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

		function check (d, ar) {
			let ok = true;
			for (let i = 0; ok && i < ar.length; i++) {
				if (i%2 == 0)
					ok = ar[i] % d == 0n;
				else
					ok = ar[i] % d != 0n;
			}
			return ok ? d : 0;
		}

		const ans = check(a[0], a) || check(a[1], a.slice(1));

		console.log(ans.toString());
	}
}

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 => BigInt(x));

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

		function check (d, ar) {
			let ok = true;
			for (let i = 0; ok && i < ar.length; i++) {
				ok = i&1 ? ar[i]%d != 0n : ar[i]%d == 0n;
			}
			return ok ? d : 0n;
		}

		const ans = check(a[0], a) || check(a[1], a.slice(1));

		console.log(ans.toString());
	}
}

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

		function check (d, ar) {
			let ok = true;
			for (let i = 0; ok && i < ar.length; i++) {
				ok = i&1 ? ar[i]%d != 0 : ar[i]%d == 0;
			}
			return ok ? d : 0;
		}

		const ans = check(a[0], a) || check(a[1], a.slice(1));

		console.log(ans);
	}
}