#2202

Maximize the Topmost Element After K Moves

expert · 1200 · lc medium +32 · verified · 24% accepted · 650 likes · top 3%

Description

You are given a 0-indexed integer array nums representing a pile where nums[0] is the topmost element.

Each move allows you to either:

- Remove the topmost element (if the pile is non-empty).

- Place any previously removed element back onto the top.

You are also given an integer k representing the exact number of moves you must perform.

Return the maximum value that can appear at the top of the pile after exactly k moves. If the pile cannot be non-empty after k moves, return -1.

Example 1:

Input: nums = [5,2,2,4,0,6], k = 4
Output: 5
Explanation:
One of the ways we can end with 5 at the top of the pile after 4 moves is as follows:
- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6].
- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6].
- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6].
- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6].
Note that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.

Example 2:

Input: nums = [2], k = 1
Output: -1
Explanation:
In the first move, our only option is to pop the topmost element of the pile.
Since it is not possible to obtain a non-empty pile after one move, we return -1.

Code

1
2
3