KatInterview

Best Self-Matching Count After Removing Array Elements

Dynamic ProgrammingModel answer
HardModel answerDynamic Programmingdynamic-programminglongest-increasing-subsequencebinary-search

Last 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,000
  • 1 <= 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.