Given array A[] of size N, the task is to find the number of operations to empty the array by performing the following operation one or more times. In one operation choose any strictly increasing subsequence and delete it from A[].
Examples:
Input: A[] = {2, 1, 4, 5, 3}
Output: 2
Explanation: Following operations are performed to empty the array:
- Choosing increasing subsequence {2, 4, 5} and removing it from A[], A[] becomes {1, 3}
- Choosing increasing subsequence {1, 3} and removing it from A[], A[] becomes empty.
Input: A[] = {0, 0, 0, 0}
Output: 4
Approach: The idea is to use a Priority Queue data structure to solve this problem.
Iterate over the array and keep inserting new element to priority queue, if given element is inserted at non-starting position than delete element just previous to that position.
Below are the steps for the above approach:
- Create priority queue pq[] using a multiset container to store the array elements in sorted order.
- Iterate from 0 to N – 1.
- For each iteration, insert the current element in pq[].
- For each iteration, search the current element in pq[].
- If the current element is at the initial position in the priority queue, move to the next iteration, else erase the previous element in the priority queue.
- Return the size of pq[] which will be the answer.
Below is the code for the above approach:
C++
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Related Articles :
Stay connected with us on social media platform for instant update click here to join our Twitter, & Facebook We are now on Telegram. Click here to join our channel (@TechiUpdate) and stay updated with the latest Technology headlines. For all the latest Technology News Click Here