Problem Description
Given an integer array nums where each element is 1, 2, or 3, the goal is to make nums non-decreasing by removing the minimum number of elements. A non-decreasing array in this scenario means that all 1's (if any) appear first, followed by 2's, and then 3's. You must decide which elements to remove such that the overall sequence becomes sorted in non-decreasing order, while minimizing the removals.
Key Insights
- The target non-decreasing order is: first a block of 1's, then 2's, and finally 3's.
- Instead of focusing on removals, we can focus on retaining the longest subsequence that already follows this order.
- This problem is equivalent to finding the maximum subsequence (not necessarily contiguous) that is non-decreasing.
- Use dynamic programming with three states representing the segments (for 1's, then 2's, then 3's).
- The minimum operations required equals the array length minus the length of the longest valid subsequence.
Space and Time Complexity
Time Complexity: O(n) – we iterate over the array once updating our DP states in constant time. Space Complexity: O(1) – we maintain only three counters for the DP approach.
Solution
We solve the problem using a dynamic programming approach with three states:
- dp1: Maximum length of a subsequence that contains only 1's.
- dp2: Maximum length of a subsequence that is non-decreasing and can include 1's followed by 2's.
- dp3: Maximum length of a subsequence that is non-decreasing and can include 1's, then 2's, then 3's.
For each element:
- If the element is 1, it can extend the dp1 subsequence.
- If the element is 2, it can either start a new segment after dp1 or extend the current dp2, so dp2 is updated to the maximum of (dp1 and dp2) plus one.
- If the element is 3, it can only be appended if a valid dp2 or dp3 sequence exists, hence dp3 is updated to max(dp2, dp3) plus one.
Finally, the maximum valid subsequence length is max(dp1, dp2, dp3) and the answer is the total number of elements minus this value.