|
| 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 | +} |
0 commit comments