Ctrl K

Best Top After Moves

Medium
A stack of numbered cards is given as the array pile, where pile[0] is the top card. In one move you can do one of two things: - if the stack is not empty, take the top card off and set it aside; - if any cards have been set aside, put any one of them back on top of the stack. You must make exactly moves moves. Return the largest number that can end up on the top card afterwards. If the stack is bound to be empty after exactly moves moves, return -1.
Example 1
pile=[3, 8, 1, 6], moves=2 → 3

You can take two cards off and leave 1 on top, or take the 3 off and put it right back, leaving 3 on top. The 8 cannot end on top in two moves: reaching it and putting it back takes three. The answer is 3.

Example 2
pile=[4], moves=3 → -1

With a single card the moves alternate: take, return, take. After three moves the stack is empty, so the answer is -1.

Example 3
pile=[2, 5, 9], moves=4 → 9

Take all three cards off and put the 9 back: exactly four moves.

Constraints
  • 1 ≤ len(pile) ≤ 10⁵
  • 0 ≤ pile[i] ≤ 10⁹
  • 0 ≤ moves ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumFewest Jumps to the End MediumReach the Last Cell MediumAs Many Trades as You Like MediumWhere to Start the Lap Medium
loading Python…
Input
pile=[3, 8, 1, 6], moves=2
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 150 tests on the server, hidden ones included.