You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split.
Example 1:
Input: [1,2,3,3,4,5]
Output: True
Explanation:
You can split them into two consecutive subsequences :
1, 2, 3
3, 4, 5
Example 2:
Input: [1,2,3,3,4,4,5,5]
Output: True
Explanation:
You can split them into two consecutive subsequences :
1, 2, 3, 4, 5
3, 4, 5
class Solution {
public boolean isPossible(int[] nums) {
if (nums == null || nums.length <= 2) {
return false;
}
Map<Integer, Integer> freq = new HashMap<>();
Map<Integer, Integer> need = new HashMap<>();
for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
for (int num : nums) {
if (freq.get(num) == 0) continue;
// Current num can be appended to a subsequence
if (need.getOrDefault(num, 0) > 0) {
need.put(num, need.get(num) - 1);
need.put(num + 1, need.getOrDefault(num + 1, 0) + 1);
}
// Current num be the start of a new subsequence
else if (freq.getOrDefault(num + 1, 0) > 0 && freq.getOrDefault(num + 2, 0) > 0) {
freq.put(num + 1, freq.get(num + 1) - 1);
freq.put(num + 2, freq.get(num + 2) - 1);
need.put(num + 3, need.getOrDefault(num + 3, 0) + 1);
}
// We can not split the array into subsequences with at least 3 consecutive numbers due to current number
else {
return false;
}
freq.put(num, freq.get(num) - 1);
}
return true;
}
}