FastPrepMaximum Distinct Values After Unit Adjustments

Maximum Distinct Values After Unit Adjustments

Birla Pivot logoBirla Pivot● MediumFULLTIMEOA

Problem statement

You are given an integer array values. Maximize the number of distinct integers in the resulting array.

For this exercise, each index may be selected at most once. At a selected index, either add 1 or subtract 1 from its original value. You may also leave an index unchanged. Choices at different indices are independent.

Return the maximum possible number of distinct values. Return only the count; you do not need to return the modified array.

Function

maximumDistinct(values: int[]) → int

Examples

Example 1

values = [1,1,1,1]return = 3

Change the first three indices to 0, 1, and 2, and leave the last as 1. The resulting array [0,1,2,1] has 3 distinct values. Every original value is 1, so only 0, 1, and 2 are reachable; a fourth distinct value is impossible.

Example 2

values = [1,1,2,2,3,3]return = 5

One feasible result is [0,1,2,3,4,3], which has 5 distinct values. Every allowed result lies between 0 and 4, so 5 is also an upper bound.

Example 3

values = [-1,-1,0,0]return = 4

Choose [-2,-1,0,1]. Each index changes by at most one, and all 4 values are distinct. No array of length 4 can contain more distinct values.

Constraints

  • 1 <= values.length <= 100000.
  • -10^9 <= values[i] <= 10^9.
  • The size and value bounds are practice assumptions; the report does not state them.

More Birla Pivot problems

See Birla Pivot hiring insights
Saved
public int maximumDistinct(int[] values) {
    // Write your solution here.
}
values[1,1,1,1]
expected3
Checking account…