Input: arr[] = [5, 2, 2, 4, 0, 6], K = 4
Output: 5
Explanation: The 4 operations are as:
- Remove the topmost element = 5. The arr becomes [2, 2, 4, 0, 6].
- Remove the topmost element = 2. The arr becomes [2, 4, 0, 6].
- Remove the topmost element = 2. The arr becomes [4, 0, 6].
- Add 5 back onto the arr. The arr becomes [5, 4, 0, 6].
Here 5 is the largest answer possible after 4 moves.
Input: arr[] = [2], K = 1
Output: -1
Explanation: Only one move can be applied and in the first move.
The only option is to remove the first element of the arr[].
If that is done the array becomes empty. So answer is -1
Follow the illustration shown below for a better understanding.
For example arr[] = {5, 2, 2, 4, 0, 6}, K = 4
1st Operation:
=> Remove 5. arr[] = {2, 2, 4, 0, 6}
=> maximum = 5, K = 4 - 1 = 3
2nd Operation:
=> Remove 2. arr[] = {2, 4, 0, 6}
=> maximum = max (5, 2) = 5, K = 3 - 1 = 2
3rd Operation:
=> Remove 2. arr[] = {4, 0, 6}
=> maximum = max (5, 2) = 5, K = 2 - 1 = 1
4th Operation:
=> Here the current 2nd element i.e. 0 is less than 5.
=> So add 5 back in the array. arr[] = {5, 4, 0, 6}
=> maximum = max (5, 0) = 5, K = 1 - 1 = 0
Therefore the maximum possible first element is 5.