[LeetCode] Split Array into Consecutive Subsequences

659. Split Array into Consecutive Subsequences

You are given an integer array nums that is sorted in non-decreasing order.

Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:

  • Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).
  • All subsequences have a length of 3 or more.
    Return true if you can split nums according to the above conditions, or false otherwise.

A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
map<int, int> count;
unordered_map<int, int> end;
public:
bool isPossible(vector<int>& nums) {
for(auto n : nums) count[n]++;
for(auto n : nums) {
if(!count[n]) continue;
count[n]--;

if(end[n-1] > 0) {
end[n-1]--;
end[n]++;
}else if(count[n + 1] > 0 and count[n + 2] > 0) {
count[n+1]--;
count[n+2]--;
end[n+2]++;
} else return false;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/split-array-into-consecutive-subsequences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.