|
| 1 | +# 2369. Check if There is a Valid Partition For The Array |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array, Dynamic Programming. |
| 5 | +- Similar Questions: . |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +You are given a **0-indexed** integer array `nums`. You have to partition the array into one or more **contiguous** subarrays. |
| 10 | + |
| 11 | +We call a partition of the array **valid** if each of the obtained subarrays satisfies **one** of the following conditions: |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | +- The subarray consists of **exactly** `2` equal elements. For example, the subarray `[2,2]` is good. |
| 16 | + |
| 17 | +- The subarray consists of **exactly** `3` equal elements. For example, the subarray `[4,4,4]` is good. |
| 18 | + |
| 19 | +- 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. |
| 20 | + |
| 21 | + |
| 22 | +Return `true`** if the array has **at least** one valid partition**. Otherwise, return `false`. |
| 23 | + |
| 24 | + |
| 25 | +Example 1: |
| 26 | + |
| 27 | +``` |
| 28 | +Input: nums = [4,4,4,5,6] |
| 29 | +Output: true |
| 30 | +Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6]. |
| 31 | +This partition is valid, so we return true. |
| 32 | +``` |
| 33 | + |
| 34 | +Example 2: |
| 35 | + |
| 36 | +``` |
| 37 | +Input: nums = [1,1,1,2] |
| 38 | +Output: false |
| 39 | +Explanation: There is no valid partition for this array. |
| 40 | +``` |
| 41 | + |
| 42 | + |
| 43 | +**Constraints:** |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +- `2 <= nums.length <= 105` |
| 48 | + |
| 49 | +- `1 <= nums[i] <= 106` |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +## Solution |
| 54 | + |
| 55 | +```javascript |
| 56 | +/** |
| 57 | + * @param {number[]} nums |
| 58 | + * @return {boolean} |
| 59 | + */ |
| 60 | +var validPartition = function(nums) { |
| 61 | + var dp = Array(nums.length + 1); |
| 62 | + dp[nums.length] = true; |
| 63 | + for (var i = nums.length - 1; i >= 0; i--) { |
| 64 | + dp[i] = (nums[i] === nums[i + 1] && dp[i + 2]) |
| 65 | + || (nums[i] === nums[i + 1] && nums[i + 1] === nums[i + 2] && dp[i + 3]) |
| 66 | + || (nums[i] + 1 === nums[i + 1] && nums[i + 1] + 1 === nums[i + 2] && dp[i + 3]); |
| 67 | + } |
| 68 | + return dp[0]; |
| 69 | +}; |
| 70 | +``` |
| 71 | + |
| 72 | +**Explain:** |
| 73 | + |
| 74 | +nope. |
| 75 | + |
| 76 | +**Complexity:** |
| 77 | + |
| 78 | +* Time complexity : O(n). |
| 79 | +* Space complexity : O(n). |
0 commit comments