want to find CIS,
but make sure it's cis and length >= 3, make sure num, num+1, num+2 exists in the following nums
count: map[number, freq count => how many keys not checked]
canAppend: map[append From Which number Ending, how many subsequence has created]
ex: 1 1 2 2 3 3 4
1. ๅต็ซๆฐ็ subsequnce
่ตทๅง by ๆๆธ x, ้ฃ่ฆ็ขบไฟ x+1, x+2 ้ฝๆ็ซ
ex: ่ตทๅง by 1, ้ฃ 2 3 ้ฝ็ขบไฟๆ็จ, countโ
1 x x 2 x x 3
2. append from ๆ subseq
1 x x 2 x x 3 xxxx [4], ๅ่จญๅทฒ็ถๆๆขๆ็ subsequence, ๅพ้ข็ดๆฅๆฅไธ
why append, ็บไป้บผไธ้ๅไธๅๆฐ็ subsequence โ ๅ ็บ ็ดๆฅ append ๅฏไปฅ็ขบไฟไธๅฎๆๅ, ้ๅไธๅๆฐ็ , ้่ฆ็ขบๅฎๅพ้ขๆ 5, 6
if (canAppend.getOrDefault(num-1, 0) > 0) {
canAppend.put(num-1, canAppend.get(num-1)-1);
canAppend.put(num, canAppend.getOrDefault(num, 0) + 1);
ๅฆๆ current num ๅ้ข็ๆธๅญ, ๆๆขๆ็ subsequence, ้ฃๅฏไปฅๆฟไพ็นผ็บๆผๆฅ,
ๆไปฅ่ฎๆ
canAppend[num-1]โ;
canAppend[num]++,
ๅฆๆ้ฝๆฒๆๆขๆ็ subsequnce ๅญๅจ, ้ฃๅฐฑ่ฆๅ 1. โ ๅต็ซๆฐ็ subsequnce
} else { // start by num
if (count.getOrDefault(num+1, 0) == 0 || count.getOrDefault(num+2, 0) == 0) {
return false;
}
count.put(num+1, count.get(num+1)-1); // num+1 ็จ้--
count.put(num+2, count.get(num+2)-1); // num+2 ็จ้--
canAppend.put(num+2, canAppend.getOrDefault(num+2, 0) + 1);
}
// ๅฆๆญค, ๅจ num+2, ๆๆขๆ็ subsequnce ++
canAppend.put(num+2, canAppend.getOrDefault(num+2, 0) + 1);
time: O(n)
space:O(n)
class Solution {
public boolean isPossible(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 = new HashMap<>(); // 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 num
if (count.getOrDefault(num+1, 0) == 0 || count.getOrDefault(num+2, 0) == 0) {
return false;
}
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);
}
}
return true;
}
}