Maximizing the Magic Value

3.8

6 votes
Sets, C++, Observation, Basic Math, Math
Problem

Given an array A of N integers, the goal is to rearrange the elements in the array A so that the magic value of the array is maximized.

The magic value is calculated by finding the length of the longest increasing subsequence of the original array A and the longest increasing subsequence of the reverse of the array A. The magic value is defined as the minimum of these two lengths. The task is to rearrange the elements in A to obtain the maximum possible magic value.

A sequence consisting of N elements a1,a2,,aN. A subsequence ai1,ai2,,aik where 1i1<i2<<ikN is called increasing if ai1<ai2<<aik. An increasing subsequence is called the longest if it has the maximum length among all increasing subsequences.

Input format

  • The first line contains a single integer T denoting the number of test cases.
  • The first line of each test case contains the integer N, the number of elements in the arrays A.
  • The second line will contain N space-separated integers, the elements of the array A.

Output format

For each test case, print the maximum possible magic value after rearranging the elements in A

Constraints

1T101N1050A[i]109  i[1,N]

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

For test case 1: As all the numbers in the array are the same, the longest increasing subsequence is just one element. Therefore, the magic value is 1.

For test case 2: Rearrange the elements in the array to [2,4,5,5,4,2]. The longest increasing subsequence in the original array is [2,4,5] and in the reverse of the array is [2,4,5]. Therefore, the magic value is 3.

Editor Image

?