2023-08-13 Daily Challenge
Today I have done leetcode's August LeetCoding Challenge with cpp
.
August LeetCoding Challenge 13
Description
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:
- 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 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
.
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 <= 105
1 <= nums[i] <= 106
Solution
auto speedup = [](){
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
return 0;
}();
class Solution {
public:
bool validPartition(vector<int>& nums) {
int len = nums.size();
vector<bool> valid(len + 1);
valid[0] = true;
if(nums[0] == nums[1]) valid[2] = true;
for(int i = 3; i <= len; ++i) {
if(valid[i - 2] && nums[i - 2] == nums[i - 1]) {
valid[i] = true;
}
if(valid[i - 3] && ((nums[i - 3] == nums[i - 2] && nums[i - 3] == nums[i - 1]) ||
(nums[i - 3] + 1 == nums[i - 2] && nums[i - 2] + 1 == nums[i - 1]))) {
valid[i] = true;
}
}
return valid.back();
}
};
// Accepted
// 117/117 cases passed (65 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 92.92 % of cpp submissions (83.9 MB)