Problem
You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.
We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:
- The subarray consists of exactly
2equal elements. For example, the subarray[2,2]is good. - The subarray consists of exactly
3equal elements. For example, the subarray[4,4,4]is good. - The subarray consists of exactly
3consecutive increasing elements, that is, the difference between adjacent elements is1. For example, the subarray[3,4,5]is good, but the subarray[1,3,5]is not.
Return true if the array has at least one valid partition. Otherwise, return false.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - TD DP with Memo
Since elements can satisfy more than one rule, this becomes an optimization problem, making dynamic programming a suitable approach.
The three scenarios to check are:
- Two consecutive equal elements
- Three consecutive equal elements
- Three consecutive increasing elements
Code
| |
Complexity
- ⏰ Time complexity:
O(n).- Each index is visited at most once due to memoization.
- For each call, only a constant number of checks (at most 3) are performed.
- 🧺 Space complexity:
O(n)- O(n) for the memoization array (
dp). - O(n) for the recursion stack in the worst case.
- O(n) for the memoization array (