KatInterview

Most Distinct Values After Shifting Each Element

Trees & GraphsAuto-graded · 22 test cases
HardAuto-gradedTrees & Graphsbipartite-matchinghopcroft-karpgraphs

Last updated

Choose one shift per element from a given list to maximize distinct results; tests recognizing the problem as bipartite matching and implementing Hopcroft-Karp efficiently.

You are given an integer array values and a list shifts of pairwise distinct integers.

For every position i, pick exactly one shift s from shifts and replace values[i] with values[i] + s. Each position chooses on its own, and the same shift may be used for any number of positions.

Return the largest possible number of distinct integers in the array after all positions have been shifted.

Notes

  • Only the count of distinct results matters, not which shifts achieve it.
  • Positions that end up duplicating another result are fine. They still receive some shift, and the count is simply of different values present.

Function

def max_distinct_after_shift(values: List[int], shifts: List[int]) -> int:

Constraints

  • 1 <= len(values) <= 10^5
  • 1 <= len(shifts) <= 100
  • -10^9 <= values[i], shifts[j] <= 10^9
  • All entries of shifts are distinct.

Examples

Example 1

Input: max_distinct_after_shift([1, 2, 3], [0, 10])

Output: 3

Example 2

Input: max_distinct_after_shift([1, 1, 1], [0, 1])

Output: 2

Hints

Hint 1

Think about which final values each position is able to reach. Two positions with the same original value reach exactly the same set, but positions with different original values can also share reachable values.

Hint 2

Counting min(frequency, number of shifts) for each original value and summing sounds tempting, but different groups can compete for the same target values. Try values = [1,1,2,2], shifts = [0,1].

Hint 3

Model it as a bipartite graph: positions on one side, reachable final values on the other. The answer is the size of a maximum matching. With up to 10^7 edges, use Hopcroft-Karp, and note that if len(shifts) >= len(values) the answer is simply len(values).