Check if There is a Valid Partition For The Array LeetCode solution in Python
1# Runtime: 920 ms (Top 32.4%) | Memory: 30.14 MB (Top 95.0%)234class Solution:5def validPartition(self, nums: List[int]) -> bool:6n = len(nums)78dp = [False] * 39dp[0] = True # An empty partition is always valid1011for i in range(2, n + 1):12ans = False1314if nums[i - 1] == nums[i - 2]:15ans = ans or dp[(i - 2) % 3]16if i >= 3 and nums[i - 1] == nums[i - 2] == nums[i - 3]:17ans = ans or dp[(i - 3) % 3]18if i >= 3 and nums[i - 1] == nums[i - 2] + 1 == nums[i - 3] + 2:19ans = ans or dp[(i - 3) % 3]2021dp[i % 3] = ans2223return dp[n % 3]