Skip to content

Commit 914db0a

Browse files
committed
leetcode
1 parent 1ed819f commit 914db0a

3 files changed

+80
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
3+
-* 2369. Check if There is a Valid Partition For The Array *-
4+
5+
You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.
6+
7+
We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:
8+
9+
The subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good.
10+
The subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good.
11+
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.
12+
Return true if the array has at least one valid partition. Otherwise, return false.
13+
14+
15+
16+
Example 1:
17+
18+
Input: nums = [4,4,4,5,6]
19+
Output: true
20+
Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].
21+
This partition is valid, so we return true.
22+
Example 2:
23+
24+
Input: nums = [1,1,1,2]
25+
Output: false
26+
Explanation: There is no valid partition for this array.
27+
28+
29+
Constraints:
30+
31+
2 <= nums.length <= 105
32+
1 <= nums[i] <= 106
33+
34+
35+
*/
36+
class Solution {
37+
bool validPartition(List<int> nums) {
38+
List<bool> vp = List.filled(nums.length + 1, true);
39+
vp[0] = true;
40+
41+
if (nums[1] == nums[0]) {
42+
vp[2] = true;
43+
}
44+
for (int i = 2; i < nums.length; i++) {
45+
if (nums[i] == nums[i - 1]) {
46+
vp[i + 1] = vp[i + 1] || vp[i - 1];
47+
}
48+
if (nums[i] == nums[i - 1] && nums[i] == nums[i - 2]) {
49+
vp[i + 1] = vp[i + 1] || vp[i - 2];
50+
}
51+
if (nums[i] == nums[i - 1] + 1 && nums[i] == nums[i - 2] + 2) {
52+
vp[i + 1] = vp[i + 1] || vp[i - 2];
53+
}
54+
}
55+
return vp[nums.length];
56+
}
57+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package main
2+
3+
func validPartition(nums []int) bool {
4+
n := len(nums)
5+
vp := make([]bool, n+1)
6+
vp[0] = true
7+
8+
if nums[1] == nums[0] {
9+
vp[2] = true
10+
}
11+
for i := 2; i < n; i++ {
12+
if nums[i] == nums[i-1] {
13+
vp[i+1] = vp[i+1] || vp[i-1]
14+
}
15+
if nums[i] == nums[i-1] && nums[i] == nums[i-2] {
16+
vp[i+1] = vp[i+1] || vp[i-2]
17+
}
18+
if nums[i] == nums[i-1]+1 && nums[i] == nums[i-2]+2 {
19+
vp[i+1] = vp[i+1] || vp[i-2]
20+
}
21+
}
22+
return vp[n]
23+
}

CheckIfThereIsAValidPartitionForTheArray/check_if_there_is_a_valid_partition_for_the_array.md

Whitespace-only changes.

0 commit comments

Comments
 (0)