As reported: Amazon SDE2 online assessment on HackerRank (June 2025), question 2 of 2.
A client buys servers from n available ones; server i has computational power powers[i]. The chosen servers must be arrangeable in a circle so that every two adjacent servers — including the last and the first — differ in power by at most 1.
Formally, a subsequence candidate of length k qualifies if it can be rearranged so that |candidate[i] − candidate[i+1]| ≤ 1 for 0 ≤ i < k−1 and |candidate[k−1] − candidate[0]| ≤ 1. Return the maximum number of servers the client can buy.
Example 1
powers = [4,3,5,1,2,2,1]
Output: 5
[3,1,2,2,1] can be arranged as [2,1,1,2,3]: every neighbour pair, including 3 and the first 2, differs by at most 1. Valid smaller choices include [1,2,2,1] and [3,1,2,2] (as [1,2,3,2]); [3,1,2] and [4,3,5] are not valid.
Example 2
powers = [3,7,5,1,5]
Output: 2 ([5,5])
Constraints: 1 ≤ n ≤ 2 · 10⁵; 0 ≤ powers[i] ≤ 10⁹.
Clarifications
- A single server is a valid choice, so the answer is at least
1. - Servers of equal power may all be used.
Code runner format: one line: powers as a JSON array. Implement getMaxServers(powers); the harness prints the maximum.