Ctrl K

Values One Apart

Easy
You are given an integer array values. Pick some of its elements (any of them may be skipped) so that the largest picked value is exactly 1 greater than the smallest one. Return the largest number of elements you can pick this way. If no such pick exists (for instance, all values are equal or no two of them differ by 1), return 0.
Example 1
values=[4, 7, 5, 4, 6, 5, 4] → 5

Take every 4 and every 5: [4, 5, 4, 5, 4] has maximum 5 and minimum 4, five elements in total. Pairing 5 with 6 or 6 with 7 gives fewer.

Example 2
values=[10, 12, 14] → 0

No two values differ by exactly 1, so the answer is 0.

Example 3
values=[-1, 0, 0, -1, 2] → 4
Constraints
  • 1 ≤ len(values) ≤ 2·10⁴
  • -10⁹ ≤ values[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Candidate With Most Votes EasyPresent in Every List EasyMore Than a Third of the Votes MediumMost Common Values MediumJobs With a Cooldown Medium
loading Python…
Input
values=[4, 7, 5, 4, 6, 5, 4]
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 115 tests on the server, hidden ones included.