classSolution {publicbooleanisPossible(int[] nums) {/* 0. count[x] == 0 continue; 1. start by x, x+1, x+2, used, count--, canAppend[x+2]++ 2. canAppend[x-1] > 0, means we can append by before subsequence, canAppend[x-1]--. canAppend[x]++ */Map<Integer,Integer> count =newHashMap<>(); // map[number, freq count => how many keys not checked] Map<Integer, Integer> canAppend = new HashMap<>(); // map[append From Which number Ending, how many subsequence has created]
for (int num : nums) {count.put(num,count.getOrDefault(num,0) +1); }for (int num : nums) {if (count.get(num) ==0) continue;count.put(num,count.get(num)-1);if (canAppend.getOrDefault(num-1,0) >0) {canAppend.put(num-1,canAppend.get(num-1)-1);canAppend.put(num,canAppend.getOrDefault(num,0) +1); } else { // start by numif (count.getOrDefault(num+1,0) ==0||count.getOrDefault(num+2,0) ==0) {returnfalse; }count.put(num+1,count.get(num+1)-1);count.put(num+2,count.get(num+2)-1);canAppend.put(num+2,canAppend.getOrDefault(num+2,0) +1); } }returntrue; }}