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:
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).
Input: nums = [1,2,3,3,4,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,5] --> 1, 2, 3
[1,2,3,3,4,5] --> 3, 4, 5
Input: nums = [1,2,3,3,4,4,5,5]
Output: true
Explanation: nums can be split into the following subsequences:
[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5
[1,2,3,3,4,4,5,5] --> 3, 4, 5
Input: nums = [1,2,3,4,4,5]
Output: false
Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
nums is sorted in non-decreasing order.The task is to determine if we can split a given array into consecutive subsequences of length at least 3. The approach involves using two hash maps:
frequency map to keep track of the remaining occurrences of each element.appendNeeded map to track the need to append an element to a previously formed subsequence.The basic greedy strategy is:
num:num can be added to an existing subsequence where it can help form a valid consecutive sequence.num can't be added to any existing subsequence, try to start a new subsequence from it.frequency map to track the available counts of each number.appendNeeded map to track if a number needs to be the next element in a subsequence.num in the input:frequency of num is zero, continue, meaning it's already used.num can be appended to a subsequence (i.e., appendNeeded[num] > 0), reduce the need and increase the need for the next number.num can't be appended, try starting a new subsequence num, num+1, num+2 and update the necessary maps.