You are given an integer array nums where each element is exactly 1, 2, or 3. Your goal is to make the array non-decreasing (sorted in ascending order) by performing the minimum number of removal operations.
In each operation, you can remove any element from the array. The challenge is to find the minimum number of elements to remove so that the remaining elements form a non-decreasing sequence.
Example: If nums = [2,1,3,2,1], you could remove the elements at indices 1 and 4 (both 1's) to get [2,3,2], then remove one more 2 to get [2,3] which is non-decreasing. The answer would be 3 operations.
Key insight: This is equivalent to finding the longest non-decreasing subsequence and subtracting its length from the total array length!
Input & Output
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 3
- Each element is guaranteed to be 1, 2, or 3