Best Self-Matching Count After Removing Array Elements
Dynamic ProgrammingModel answerLast updated
Delete any elements from an array so the most remaining values equal their new 1-based position. Reduce it to a longest-chain problem solved in O(n log n).
You are given an integer array nums. You may delete any number of elements, including none or all of them. The survivors keep their relative order and are renumbered starting from 1.
After renumbering, call a survivor matched if its value equals its new 1-based position. Return the largest number of matched survivors you can get with the best choice of deletions.
Implement:
def max_matched(nums: list[int]) -> int:
...
Constraints
1 <= len(nums) <= 200,0001 <= nums[i] <= 200,000
Examples
Example 1
nums = [1, 5, 2, 3]
Output: 3
Delete the 5. The array becomes [1, 2, 3], and all three values equal their positions.
Example 2
nums = [2, 2, 3]
Output: 2
Delete nothing. The array is [2, 2, 3]. Position 1 holds 2 (no match), position 2 holds 2 (match), and position 3 holds 3 (match). That gives 2 matches.
Points to consider
- Values may exceed the array length, and duplicates are allowed.
- If nothing can ever match, the answer is
0. - An O(n²) approach is too slow for the given limits.
What is expected
Explain your approach, justify why it is correct, state its time and space complexity, and give code.
Hints
Hint 1
For an element at 1-based index i with value v, count how many elements before it must be deleted for it to land on position v. Which elements can never match under any choice?
Hint 2
Take two elements you want matched, earlier (i, v) and later (j, w). Work out when it is possible to keep exactly w - v - 1 of the j - i - 1 elements between them. The answer gives two simple inequalities, one on the values and one on the deletion counts i - v and j - w.
Hint 3
The problem becomes a longest chain with strictly increasing value and non-decreasing deletion count. Sort by value ascending, break ties by deletion count descending, then find the longest non-decreasing subsequence of deletion counts with binary search.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Reformulating the problem
Use 1-based original indices. For an element at index i with value v, define its deletion debt d = i - v.
If this element is to be matched, it must end up at position v. That means exactly v - 1 elements before it are kept, so exactly i - 1 - (v - 1) = i - v = d elements before it are deleted. This gives two facts:
- If
d < 0(the value exceeds its index), the element can never match, so discard it. - Otherwise
dis the exact number of deletions that must occur before it.
When can two matched elements coexist?
Suppose (i, v) is matched and (j, w) is a later matched element. Two conditions are needed.
w > v. Positions strictly increase along a subsequence.d_j >= d_i. Between them there arej - i - 1original elements, and we must keep exactlyw - v - 1of them. The number deleted in between is(j - i - 1) - (w - v - 1) = d_j - d_i. This must lie between 0 andj - i - 1. The upper bound follows fromw > v, so the real requirement isd_j >= d_i.
These two conditions imply j > i, since j = w + d_j > v + d_i = i. The original order therefore takes care of itself.
So the task is: among points (v, d) with d >= 0, find the longest chain where v is strictly increasing and d is non-decreasing.
Why the chain is achievable
Necessity is shown above: any set of matched elements, in subsequence order, satisfies both conditions pairwise.
For sufficiency, take any valid chain and build the subsequence like this:
- Before the first chain element
(i1, v1), keep anyv1 - 1of thei1 - 1earlier elements. This is possible becaused1 >= 0. - Between consecutive chain elements, keep any
w - v - 1of thej - i - 1elements in between. This is possible by the two conditions. - After the last chain element, delete everything.
Every chain element now sits at its own value. Filler elements may happen to match too, which would only raise the count, but the maximum over all chains is already the optimum, so the answer equals the longest chain length.
Algorithm
- Build the points
(v, i - v)for every element withv <= i. - Sort by
vascending, and for equalvbyddescending. - Compute the longest non-decreasing subsequence of the
dvalues using the patience-sorting technique, withbisect_right.
The tie-break matters. Two points with the same v cannot both be matched, since they would need the same position. With d descending among equal v, a non-decreasing subsequence of d can never take two of them, so strictness in v is enforced automatically.
Code
from bisect import bisect_right
def max_matched(nums: list[int]) -> int:
points = []
for i, v in enumerate(nums, start=1):
if v <= i:
points.append((v, i - v))
# v ascending; for equal v, d descending so at most one of them is chained
points.sort(key=lambda p: (p[0], -p[1]))
tails: list[int] = []
for _, d in points:
k = bisect_right(tails, d) # non-decreasing => bisect_right
if k == len(tails):
tails.append(d)
else:
tails[k] = d
return len(tails)
Traces
[1, 5, 2, 3]: the points are(1,0),(2,1)and(3,1). The5at index 2 is dropped because5 > 2. Thedsequence is0, 1, 1, which is non-decreasing, so the answer is 3.[2, 2, 3]: the first2at index 1 is dropped. The points are(2,0)and(3,0), giving a chain of length 2.
Complexity
- Time: O(n log n), from the sort plus one binary search per candidate.
- Space: O(n) for the points and the tails array.
With n up to 200,000 this runs comfortably.
Edge cases
- All values larger than their index: no points, answer
0. - Already perfect array such as
[1, 2, 3]: every debt is 0, so the whole array is the chain. - Many duplicates, such as
[1, 1, 1, 1]: points(1,0),(1,1),(1,2),(1,3). The descending tie-break makesdread3, 2, 1, 0, whose longest non-decreasing subsequence has length 1. That is correct, since only one element can sit at position 1. - Large values: filtered out immediately, so there is no need to size anything by the maximum value.
Common mistakes
- Greedy matching (keep an element whenever it equals the current length plus one). This fails because a non-matching filler kept now can be exactly what a later match needs, and a locally good match can block a better one.
- Using
bisect_left. That finds a strictly increasing subsequence ofdand wrongly forbids two chain elements with the same debt, such as(2,1)and(3,1)in Example 1. - Forgetting the tie-break on equal values, which lets duplicates chain together.
- Index off-by-one. With 0-based
ithe debt isi + 1 - v. - Treating
d < 0as usable. It would require keeping more earlier elements than exist.
Trade-offs and validation
An O(n²) DP over pairs of points is simple and useful as a brute-force cross-check on small inputs. A fully exhaustive subset search is also practical for n up to about 15, and comparing it against the O(n log n) solution on random arrays is a good way to catch mistakes in the tie-break or the choice of bisect.