Construct Maximum Balanced Circle
Learn this problemProblem statement
There are n people in a row. The height of the i-th person is a[i].
You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any
adjacent people is no more than 1. For example, let heights of chosen people be
[a[i1], a[i2], ..., a[ik]], where k is the number of people you
choose. Then the condition |a[ij] - a[ij+1]| ≤ 1 should be satisfied for all
j from 1 to k - 1 and the condition |a[i1] - a[ik]| ≤ 1
should be also satisfied. |x| means the absolute value of x. It is
obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 · 10^5) —
the number of people.
The second line of the input contains n integers a[1], a[2], ..., a[n]
(1 ≤ a[i] ≤ 2 · 10^5), where a[i] is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum
balanced circle.
In the second line print k integers res[1], res[2], ..., res[k],
where res[j] is the height of the j-th person in the maximum balanced circle.
The condition |res[j] - res[j+1]| ≤ 1 should be satisfied for all j
from 1 to k - 1 and the condition |res[1] - res[k]| ≤ 1 should be
also satisfied.
Function
constructMaximumBalancedCircle(heights: int[]) → int[]Examples
Example 1
heights = [4, 3, 5, 1, 2, 2, 1]return = [2, 1, 1, 2, 3]Example 2
heights = [3, 7, 5, 1, 5]return = [5, 5]Example 3
heights = [5, 1, 4]return = [4, 5]Example 4
heights = [2, 2, 3, 2, 1, 2, 2]return = [1, 2, 2, 2, 2, 3, 2]More Microsoft problems
- Maximum Pipeline ThroughputOA · Seen Jul 2026
- Maximum Strong Team SubarrayOA · Seen Jul 2026
- Minimum Cost K-Capable ModelsOA · Seen Jul 2026
- Alphabetically Smallest PalindromeOA · Seen Jul 2026
- Maximum Reward PointsOA · Seen Jul 2026
- Maximum Strength of Every NeuronOA · Seen Jul 2026
- Neural Network Subnetwork StrengthOA · Seen Jul 2026
- XOR MultiplicationOA · Seen Jul 2026