E. Roy and Maximum Removals

E. Roy and Maximum Removals

Time Limit: 2.0 s

Memory Limit: 128.0 MB

Description

You are given an array A[] consisting of N integers.

You may perform the following operation any number of times:

• Choose any element of the current array. Let its value be x.
• If the current array contains fewer than x elements, this element cannot be chosen.
• Otherwise, you must remove exactly x elements from the array, and the chosen element must be one of them.
• The remaining x − 1 elements to remove may be any elements of the current array.

After each operation, the removed elements disappear from the array, and the array becomes shorter. You may continue performing operations while possible.

Your task is to determine the maximum total number of elements that can be removed after performing an optimal sequence of operations.

Input

  • The first line contains T (1 ≤ T ≤ 500) — the number of test cases.
  • For each test case:
    • The first line contains N (1 ≤ N ≤ 50000).
    • The second line contains N integers A1, A2, ..., AN (1 ≤ Ai ≤ \(10^9\)).
  • Sum of all N over all test cases does not exceed 50000.

Output

For each test case, output a single integer — the maximum number of elements that can be removed.

Sample

Input Output
6
1
2
4
1 2 1 2
5
7 10 2 2 4
7
5 2 3 3 3 5 1
7
5 3 3 2 4 4 4
6
4 4 4 4 4 4
0
4
4
7
7
4

Consider 4th test case :
A[] = [5, 2, 3, 3, 3, 5, 1] (N = 7)

Operation 1:

Chosen = [3]

Removed = [5, 3, 5] (remove 3 elements including chosen 3)

Remaining = [2,3,3,1]

Operation 2:

Chosen = [3]

Removed = [2,3,3] (remove 3 elements including chosen 3)

Remaining = [1]

Operation 3 :
Chosen = [1]

Removed = [1] (remove 1 elements including chosen 1)

Remaining = []
Final:

Remaining = []
Answer = 7

Information

ID
1234
Difficulty
5
Category
DP Click to Show
Tags
# Submissions
46
Accepted
22
Accepted Ratio
48%
Uploaded By

Related

In following contests:

Happy New Year 2026