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
Maximize Topmost Element After K Moves INPUT Pile (top to bottom): 5 (top) 2 7 4 1 Input Values: nums = [5, 2, 7, 4, 1] k = 2 (moves) n = 5 (length) ALGORITHM STEPS 1 Check Edge Cases k=1: return nums[1] if exists n=1, k odd: return -1 2 Identify Reachable Elements With k=2 moves, can reach: indices 0,1,2 (first k+1) 3 Find Max in Range Check first k-1 elements: nums[0]=5 (remove, put back) 4 Check Position k Remove k elements to expose nums[k]=nums[2]=7 Greedy Analysis (k=2): Option A: Remove 5, put 5 back Option B: Remove 5, remove 2 --> exposes 7 (max!) Max = max(5, 7) = 7 FINAL RESULT After k=2 moves: Move 1: Remove 5 Pile: [2,7,4,1] Removed: {5} Move 2: Remove 2 Pile: [7,4,1] Removed: {5,2} Final Pile State: 7 (top) 4 1 Output: 7 Key Insight: With exactly k moves, we can either: (1) expose element at index k by removing k elements, or (2) remove some elements and put back the maximum among removed ones. The answer is the maximum of: max(nums[0..k-2]) and nums[k] (if k < n). Greedy: always pick the larger option! TutorialsPoint - Maximize the Topmost Element After K Moves | Greedy Strategy Analysis
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.5K Views
Medium Frequency
~25 min Avg. Time
487 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen