Most Distinct Values After Shifting Each Element
Trees & GraphsAuto-graded · 22 test casesLast 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^51 <= len(shifts) <= 100-10^9 <= values[i], shifts[j] <= 10^9- All entries of
shiftsare 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).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every distinct final value needs at least one position that produces it. Pick one such "representative" position per distinct value. Then the representatives hold pairwise different values. Conversely, if we can give some set of positions pairwise different reachable values, all remaining positions can take any shift without lowering the distinct count. So the answer is the largest number of positions that can be assigned different target values, where position i may only use targets in {values[i] + s : s in shifts}.
This is a maximum bipartite matching:
- Left side: positions
0..n-1. - Right side: all reachable final values.
- Edges: position
itovalues[i] + sfor every shifts.
The matching size is the answer.
Why a simple per-group greedy fails
Summing min(count of v, len(shifts)) over each distinct original value ignores that groups can share targets. For values = [1,1,2,2], shifts = [0,1], that formula gives 4, but all results lie in {1,2,3}, so the true answer is 3. Matching resolves these conflicts correctly.
Algorithm (Hopcroft-Karp)
With up to n * m = 10^7 edges, we use Hopcroft-Karp rather than one augmenting path at a time.
- Shortcut: since shifts are distinct, any set of positions reaches at least
mdistinct targets. Ifm >= n, Hall's condition holds for all subsets and the answer isn. - BFS phase: start from all unmatched positions at distance 0. From a position, follow each target. If a target is unowned, an augmenting path exists. Otherwise move to the position owning that target, giving it the next layer distance.
- DFS phase: from each unmatched position, follow only layered edges (distance increases by exactly 1) to find a path ending at an unowned target, then flip the matching along that path. A position that fails gets distance infinity so it is not explored again in this phase.
- Repeat until BFS finds no augmenting path.
Target values are stored in a dictionary, so negative or very large numbers need no special treatment.
Why it is correct
Each successful DFS flips an alternating path and increases the matching by one. By Berge's theorem, a matching is maximum exactly when no augmenting path exists, which is when BFS fails to reach an unowned target. Combined with the reduction above, the final matching size equals the maximum number of distinct values.
Complexity
- Time:
O(E * sqrt(V))in the worst case, withE = n * mat most10^7. In practice far fewer phases are needed. - Space:
O(n * m)for the target lists and the owner map.
Reference solution
import sys
from collections import deque
from typing import List
def max_distinct_after_shift(values: List[int], shifts: List[int]) -> int:
n = len(values)
m = len(shifts)
# Shifts are distinct, so any group of at most m positions has at least
# m reachable targets (Hall's condition holds): everyone can be unique.
if m >= n:
return n
sys.setrecursionlimit(max(10000, 2 * n + 100))
targets = [[v + s for s in shifts] for v in values]
owner = {} # target value -> position currently matched to it
assigned = [-1] * n # position -> target value it is matched to, or -1
dist = [0] * n
INF = n + 1
def bfs() -> bool:
queue = deque()
for i in range(n):
if assigned[i] == -1:
dist[i] = 0
queue.append(i)
else:
dist[i] = INF
reached_free = False
while queue:
i = queue.popleft()
for t in targets[i]:
j = owner.get(t)
if j is None:
reached_free = True
elif dist[j] == INF:
dist[j] = dist[i] + 1
queue.append(j)
return reached_free
def dfs(i: int) -> bool:
for t in targets[i]:
j = owner.get(t)
if j is None or (dist[j] == dist[i] + 1 and dfs(j)):
assigned[i] = t
owner[t] = i
return True
dist[i] = INF
return False
result = 0
while bfs():
for i in range(n):
if assigned[i] == -1 and dfs(i):
result += 1
return result