Maximize Fixed Points After Deletions Problem
Description
LeetCode Problem 3920.
You are given an integer array nums.
A position i is called a fixed point if nums[i] == i.
You are allowed to delete any number of elements (including zero) from the array. After each deletion, the remaining elements shift left, and indices are reassigned starting from 0.
Return an integer denoting the maximum number of fixed points that can be achieved after performing any number of deletions.
Example 1:
Input: nums = [0,2,1]
Output: 2
Explanation:
- Delete nums[1] = 2. The array becomes [0, 1].
- Now, nums[0] = 0 and nums[1] = 1, so both indices are fixed points.
- Thus, the answer is 2.
Example 2:
Input: nums = [3,1,2]
Output: 2
Explanation:
- Do not delete any elements. The array remains [3, 1, 2].
- Here, nums[1] = 1 and nums[2] = 2, so these indices are fixed points.
- Thus, the answer is 2.
Example 3:
Input: nums = [1,0,1,2]
Output: 3
Explanation:
- Delete nums[0] = 1. The array becomes [0, 1, 2].
- Now, nums[0] = 0, nums[1] = 1, and nums[2] = 2, so all indices are fixed points.
- Thus, the answer is 3.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^5
Solution
Approach: Longest Chain With Binary Search
Keeping an element x at original index i and making it a fixed point means exactly x elements must remain before it, so we need x <= i; elements with x > i can never be fixed points. For such an element let d = i - x, the number of extra elements we are allowed to delete before it.
Take two candidates (x1, d1) at index i1 and (x2, d2) at index i2 > i1. Both can be fixed points when x1 < x2 (they must end up in that order at indices x1 and x2) and d1 <= d2: between them we have to keep exactly x2 - x1 - 1 elements out of i2 - i1 - 1, and that is possible exactly when i2 - x2 >= i1 - x1.
So the answer is the longest sequence with strictly increasing x and non-decreasing d. Sort the candidates by x ascending (ties by d descending, so two candidates with the same x are never chained) and compute the longest non-decreasing subsequence of d with binary search.
Complexity: O(n log n) time and O(n) extra space.
from bisect import bisect_right
class Solution:
def maxFixedPoints(self, nums: List[int]) -> int:
items = [(x, i - x) for i, x in enumerate(nums) if x <= i]
items.sort(key=lambda t: (t[0], -t[1]))
tails = []
for _, d in items:
pos = bisect_right(tails, d)
if pos == len(tails):
tails.append(d)
else:
tails[pos] = d
return len(tails)