Description
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 2 equal elements. For example, the subarray [2,2] is good.
The subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good.
The subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. 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.
Example 1:
Input: nums = [4,4,4,5,6]
Output: true
Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].
This partition is valid, so we return true.
Example 2:
Input: nums = [1,1,1,2]
Output: false
Explanation: There is no valid partition for this array.
Constraints:
2 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
Solution
Recursive, f(nums) = first 2-3 numbers and f(nums[i:])
.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
n
)
o(n)
o(n)
Code
class Solution:
def validPartition(self, nums: List[int]) -> bool:
memo = {}
def helper(index: int) -> bool:
if index in memo:
return memo[index]
if index == len(nums):
return True
if len(nums) - index < 2:
memo[index] = False
return memo[index]
flag1, flag2, flag3 = False, False, False
if nums[index] == nums[index + 1]:
flag1 = True
if index + 2 < len(nums):
if nums[index] == nums[index + 1] and nums[index] == nums[index + 2]:
flag2 = True
if nums[index] + 1 == nums[index + 1] and nums[index + 1] + 1 == nums[index + 2]:
flag3 = True
memo[index] = (flag1 and helper(index + 2)) or (flag2 and helper(index + 3)) or (flag3 and helper(index + 3))
return memo[index]
return helper(0)