![]() |
VOOZH | about |
Given an array arr[] and an integer k. The task is to delete k elements which are smaller than next element (i.e., we delete arr[i] if arr[i] < arr[i+1]) or become smaller than next because next element is deleted.
Note: The deletion operation should start from left to right.
Example:
Input : arr[] = [20, 10, 25, 30, 40], k = 2
Output : 25 30 40
Explanation : First we delete 10 because it follows arr[i] < arr[i+1]. Then we delete 20 because 25 is moved next to it and it also starts following the condition.Input : arr[] = [3, 100, 1], k = 1
Output : 100 1
Explanation : arr[0] < arr[1] means 3 is less than 100, so delete 3Input: arr[] = [23, 45, 11, 77, 18], k = 3
Output : 77 18
Explanation : We delete 23, 45 and 11 as they follow the condition arr[i] < arr[i+1]
The idea is to use a stack to keep track of elements we want to retain while iterating through the input array. For each element, we compare it with the top of the stack. If the current element is greater than the stack's top element and we still have deletions available, we pop elements from the stack until this condition is no longer met.
Step by step approach:
25 30 40
The idea for the single array approach is essentially the same, but we can directly use a vector as our answer array instead of a stack. Since we're building our result directly in the correct order, we don't need the extra step of transferring and reversing elements at the end, making this approach more efficient and cleaner.
25 30 40