Check if There is a Valid Partition of the Array

medium dp partition

Problem

You are given an integer array nums (2 ≤ nums.length ≤ 10⁵, 1 ≤ nums[i] ≤ 10⁶). Split it into contiguous blocks so that every block has one of exactly three shapes: two equal values like [7, 7], three equal values like [7, 7, 7], or three values that each step up by exactly 1 like [3, 4, 5]. Return true if at least one such split covers the whole array.

Every element must belong to exactly one block — no other block length or shape is allowed.

Inputnums = [4, 4, 4, 5, 6]
Outputtrue
Split as [4, 4] + [4, 5, 6]: a pair of equal values followed by three consecutive values.

def valid_partition(nums):
    n = len(nums)
    dp = [False] * (n + 1)
    dp[0] = True
    for i in range(2, n + 1):
        if dp[i - 2] and nums[i - 1] == nums[i - 2]:
            dp[i] = True
        if i >= 3 and dp[i - 3]:
            a, b, c = nums[i - 3], nums[i - 2], nums[i - 1]
            if a == b == c or (b == a + 1 and c == b + 1):
                dp[i] = True
    return dp[n]
function validPartition(nums) {
  const n = nums.length;
  const dp = new Array(n + 1).fill(false);
  dp[0] = true;
  for (let i = 2; i <= n; i++) {
    if (dp[i - 2] && nums[i - 1] === nums[i - 2]) dp[i] = true;
    if (i >= 3 && dp[i - 3]) {
      const a = nums[i - 3], b = nums[i - 2], c = nums[i - 1];
      if ((a === b && b === c) || (b === a + 1 && c === b + 1)) dp[i] = true;
    }
  }
  return dp[n];
}
boolean validPartition(int[] nums) {
    int n = nums.length;
    boolean[] dp = new boolean[n + 1];
    dp[0] = true;
    for (int i = 2; i <= n; i++) {
        if (dp[i - 2] && nums[i - 1] == nums[i - 2]) dp[i] = true;
        if (i >= 3 && dp[i - 3]) {
            int a = nums[i - 3], b = nums[i - 2], c = nums[i - 1];
            if ((a == b && b == c) || (b == a + 1 && c == b + 1)) dp[i] = true;
        }
    }
    return dp[n];
}
bool validPartition(vector<int>& nums) {
    int n = nums.size();
    vector<bool> dp(n + 1, false);
    dp[0] = true;
    for (int i = 2; i <= n; i++) {
        if (dp[i - 2] && nums[i - 1] == nums[i - 2]) dp[i] = true;
        if (i >= 3 && dp[i - 3]) {
            int a = nums[i - 3], b = nums[i - 2], c = nums[i - 1];
            if ((a == b && b == c) || (b == a + 1 && c == b + 1)) dp[i] = true;
        }
    }
    return dp[n];
}
Time: O(n) Space: O(n)