Maximize the Topmost Element After K Moves - Problem
You are given a 0-indexed integer array nums representing the contents of a pile, where nums[0] is the topmost element of the pile.
In one move, you can perform either of the following:
- If the pile is not empty, remove the topmost element of the pile.
- If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element.
You are also given an integer k, which denotes the total number of moves to be made.
Return the maximum value of the topmost element of the pile possible after exactly k moves. In case it is not possible to obtain a non-empty pile after k moves, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [5,2,7,4,1], k = 2
›
Output:
7
💡 Note:
We can remove 5 and 2 (2 moves), making 7 the topmost element. Or remove 5, then add it back, then remove it and 2 to get 7 on top.
Example 2 — All Elements Removed
$
Input:
nums = [2], k = 1
›
Output:
-1
💡 Note:
With only 1 element and 1 move, we must remove it, leaving an empty pile.
Example 3 — Return to Original
$
Input:
nums = [73,98,39,51], k = 4
›
Output:
98
💡 Note:
We can remove all 4 elements, then add back the maximum (98) to make it topmost.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ k ≤ 2 × 109
- 1 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [5,2,7,4,1] with k=2 moves
2
Process
Remove elements to reach better ones or rearrange
3
Output
Maximum possible top element: 7
Key Takeaway
🎯 Key Insight: Analyze which positions are reachable with exactly k moves, considering both removal and addition operations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code