[LeetCode] Check if There is a Valid Partition For The Array

2369. Check if There is a Valid Partition For The Array

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:

  1. The subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good.
  2. The subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good.
  3. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
int dp[101010];
bool eqtwo(vector<int>& A, int p) {
if(p + 2 > A.size()) return false;
return A[p] == A[p+1];
}
bool eqthree(vector<int>& A, int p) {
if(p + 3 > A.size()) return false;
return A[p] == A[p+1] and A[p] == A[p + 2];
}
bool incthree(vector<int>& A, int p) {
if(p + 3 > A.size()) return false;
return A[p] + 1 == A[p+1] and A[p] + 2 == A[p + 2];
}
int helper(vector<int>& A, int p) {
if(p == A.size()) return 1;
if(dp[p] != -1) return dp[p];
int& res = dp[p] = 0;
if(eqtwo(A,p)) res |= helper(A, p + 2);
if(eqthree(A,p)) res |= helper(A, p + 3);
if(incthree(A,p)) res |= helper(A, p + 3);
return res;
}
public:
bool validPartition(vector<int>& nums) {
memset(dp,-1,sizeof dp);
return helper(nums, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/07/PS/LeetCode/check-if-there-is-a-valid-partition-for-the-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.