Given a sequence, pick each value at most twice to maximize the sum, and among all maximum-sum picks output the lexicographically smallest subsequence.
Medium6GreedySortingHash mapImplementationInterviewNo attempts yetTime limit3sMemory limit512 MBJessie and James are hunting Tataramon, small creatures that live around the village. To capture one, they first have to fight it and then put it in a Tataraball.
The computer in their rocket predicted, in order, which Tataramon they will meet along their path. Every kind of Tataramon has its own number. For example, number 25 is called Pandan-kachu.
The two do not want to be greedy, so they take at most two Tataramon of each kind. At the same time, they want the sum of the numbers of every Tataramon they captured to be as large as possible.
Given the numbers of the Tataramon in the order they are encountered, pick each number at most twice so that the sum of the picked numbers is as large as possible. The captured Tataramon keep the order in which the two met them, so the answer is a subsequence of the original sequence.
The first line contains T, the number of test cases.
The first line of each test case contains an integer N. The second line contains N integers A1,A2,…,AN separated by single spaces, the numbers of the Tataramon in the order Jessie and James meet them.
For each test case, print on one line the numbers B1,B2,…,BM of the Tataramon they should capture, separated by spaces. The numbers keep the order of the input, so B1,…,BM is a subsequence of A1,…,AN.
Several subsequences can reach the maximum sum. In that case, print only the lexicographically smallest one. Every subsequence with the maximum sum has the same length, so compare two of them from the front: at the first position where they differ, the one with the smaller value comes first.