Maximize the Topmost Element After K Moves - Problem
Maximize the Topmost Element After K Moves

You have a pile of integers represented as an array nums, where nums[0] is the topmost element. Your goal is to maximize the value of the topmost element after performing exactly k moves.

In each move, you can choose one of two operations:
  • Remove the topmost element from the pile (if not empty)
  • Add back any previously removed element to the top of the pile

The challenge is to strategically use these k moves to get the maximum possible value at the top. If it's impossible to have a non-empty pile after k moves, return -1.

Example: With pile [5, 2, 2, 4, 0, 6] and k = 4 moves, you could remove the first 3 elements (getting 5, 2, 2), then add back the maximum (5) to achieve a topmost value of 5.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [5,2,2,4,0,6], k = 4
โ€บ Output: 5
๐Ÿ’ก Note: One optimal strategy: Remove elements 5,2,2 (3 moves), then add back 5 (1 move). The top element is now 5, which is the maximum possible.
example_2.py โ€” Remove Exactly k
$ Input: nums = [2], k = 1
โ€บ Output: -1
๐Ÿ’ก Note: With only one element and one move, we must remove the element, leaving an empty pile. Return -1.
example_3.py โ€” Keep Current Top
$ Input: nums = [73,63,62,16,95], k = 2
โ€บ Output: 73
๐Ÿ’ก Note: Remove top element 73 (1 move), then add it back (1 move). The pile remains [73,63,62,16,95] with top element 73.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 0 โ‰ค nums[i] โ‰ค 109
  • 1 โ‰ค k โ‰ค 2 ร— 105
  • All elements are non-negative integers

Visualization

Tap to expand
Maximize Topmost Element: Strategic AnalysisInitial State522406k = 4 movesRemove 3 Elements5224063 moves usedMax removed = 5Put Back Maximum54061 more moveTotal: 4 movesResult: 5Other ScenariosRemove 1: max(5)=5 โœ“Remove 2: max(5,2)=5 โœ“Remove 3: max(5,2,2)=5 โœ“Remove 4: nums[4]=0 โœ—Best choice: 5Time: O(n)Space: O(1)๐Ÿ’ก Key Insight: Only k+1 scenarios matter, not 2^k combinations!Greedy strategy: Always put the maximum available element on top
Understanding the Visualization
1
Analyze the Pile
Look at the pile [5,2,2,4,0,6] with k=4 moves
2
Consider Scenarios
Remove 0 elements (impossible with k=4), remove 1-3 elements + put back max, or remove 4 elements
3
Execute Best Strategy
Remove 5,2,2 (3 moves) then put back 5 (1 move)
4
Achieve Optimal Result
Top element is now 5, which is the maximum possible
Key Takeaway
๐ŸŽฏ Key Insight: Instead of exploring exponential combinations, recognize that optimal strategies follow predictable patterns - either remove some elements and put back the maximum, or remove exactly k elements to reveal a deeper element.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~18 min Avg. Time
856 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