|
| 1 | +/** |
| 2 | + * 659. Split Array into Consecutive Subsequences |
| 3 | + * https://leetcode.com/problems/split-array-into-consecutive-subsequences/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an integer array nums that is sorted in non-decreasing order. |
| 7 | + * |
| 8 | + * Determine if it is possible to split nums into one or more subsequences such that both of the |
| 9 | + * following conditions are true: |
| 10 | + * - Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more |
| 11 | + * than the previous integer). |
| 12 | + * - All subsequences have a length of 3 or more. |
| 13 | + * |
| 14 | + * Return true if you can split nums according to the above conditions, or false otherwise. |
| 15 | + * |
| 16 | + * A subsequence of an array is a new array that is formed from the original array by deleting some |
| 17 | + * (can be none) of the elements without disturbing the relative positions of the remaining |
| 18 | + * elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not). |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[]} nums |
| 23 | + * @return {boolean} |
| 24 | + */ |
| 25 | +var isPossible = function(nums) { |
| 26 | + const map = new Map(); |
| 27 | + const map2 = new Map(); |
| 28 | + |
| 29 | + for (const n of nums) { |
| 30 | + map.set(n, (map.get(n) || 0) + 1); |
| 31 | + } |
| 32 | + |
| 33 | + for (const n of nums) { |
| 34 | + if (map.get(n) === 0) continue; |
| 35 | + |
| 36 | + if ((map2.get(n) || 0) > 0) { |
| 37 | + map2.set(n, map2.get(n) - 1); |
| 38 | + map.set(n, map.get(n) - 1); |
| 39 | + map2.set(n + 1, (map2.get(n + 1) || 0) + 1); |
| 40 | + } else if ((map.get(n) || 0) > 0 && (map.get(n + 1) || 0) > 0 && (map.get(n + 2) || 0) > 0) { |
| 41 | + map.set(n, map.get(n) - 1); |
| 42 | + map.set(n + 1, map.get(n + 1) - 1); |
| 43 | + map.set(n + 2, map.get(n + 2) - 1); |
| 44 | + map2.set(n + 3, (map2.get(n + 3) || 0) + 1); |
| 45 | + } else { |
| 46 | + return false; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return true; |
| 51 | +}; |
0 commit comments