Maximize the Topmost Element After K Moves Problem
#2202
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2202.
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.
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.
Constraints:
1 <= nums.length <= 10^50 <= nums[i], k <= 10^9
Solution
Approach: Case analysis
k can be as large as 10^9, so we cannot simulate the moves. Instead we work out which values can be on top after exactly k moves.
- If
k = 0, nothing moves and the answer isnums[0]. - If the pile has one element, each move either removes it or puts it back, so after an odd number of moves the pile is empty (answer
-1) and after an even number it isnums[0]again. - Otherwise (
n ≥ 2), the firstk - 1moves can remove the firstk - 1elements, and the last move can put any one of them back, so every one ofnums[0..k-2]is a candidate. Ifk < n, thek-th move can also removenums[k-1]and leavenums[k]exposed, sonums[k]is a candidate too. The answer is the largest candidate, or-1if there is none.
Complexity: O(min(k, n)) time, O(1) extra space.
class Solution:
def maximumTop(self, nums: List[int], k: int) -> int:
if k == 0:
return nums[0]
n = len(nums)
if n == 1:
if k % 2:
return -1
return nums[0]
ans = max(nums[: k - 1], default=-1)
if k < n:
ans = max(ans, nums[k])
return ans