Given an array nums
sorted in ascending order, return true
if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3.
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) { Map<Integer, Integer> freqMap = new HashMap<>(); Map<Integer, Integer> hypoMap = new HashMap<>(); for (int num: nums) { freqMap.put(num, freqMap.getOrDefault(num, 0) + 1); } for (int num : nums) { // base case if (freqMap.get(num) == 0) { continue; } if (hypoMap.getOrDefault(num, 0) > 0) { hypoMap.put(num, hypoMap.get(num) - 1); freqMap.put(num, freqMap.get(num) - 1); hypoMap.put(num + 1, hypoMap.getOrDefault(num + 1, 0) + 1); } else if (freqMap.getOrDefault(num, 0) > 0 && freqMap.getOrDefault(num + 1, 0) > 0 && freqMap.getOrDefault(num + 2, 0) > 0) { freqMap.put(num, freqMap.get(num) - 1); freqMap.put(num + 1, freqMap.get(num + 1) - 1); freqMap.put(num + 2, freqMap.get(num + 2) - 1); hypoMap.put(num + 3, hypoMap.getOrDefault(num + 3, 0) + 1); } else { return false; } } return true; } }