Minimum Number of Increasing Subsequence to Be Removed Problem
#3231
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3231.
Given an array of integers nums, you are allowed to perform the following operation any number of times:
- Remove a strictly increasing subsequence from the array.
Your task is to find the minimum number of operations required to make the array empty.
Example 1:
Input: nums = [5,3,1,4,2]
Output: 3
Explanation:
We remove subsequences [1, 2], [3, 4], [5].
Example 2:
Input: nums = [1,2,3,4,5]
Output: 1
Example 3:
Input: nums = [5,4,3,2,1]
Output: 5
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Greedy + Binary Search
Scan nums left to right and keep the last element of every strictly increasing sequence built so far. Put each x after the sequence whose last element is the first one smaller than x; if none is smaller, x starts a new sequence. These last elements stay in non-increasing order, so that sequence is found by binary search and its last element is replaced by x. The answer is the number of sequences.
Complexity: O(n log n) time, O(n) space, where n is the length of nums.
class Solution:
def minOperations(self, nums: List[int]) -> int:
g = []
for x in nums:
l, r = 0, len(g)
while l < r:
mid = (l + r) >> 1
if g[mid] < x:
r = mid
else:
l = mid + 1
if l == len(g):
g.append(x)
else:
g[l] = x
return len(g)