Maximize the Topmost Element After K Moves — LeetCode 2202 Python Solution

MediumGreedyArray
Problem
#2202
Pattern
Greedy
Reading time
3 min

The 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.

Example

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:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2202. Maximize the Topmost Element After K Moves is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2202. Maximize the Topmost Element After K Moves?
LeetCode 2202. Maximize the Topmost Element After K Moves is rated Medium on LeetCode.
What topics does LeetCode 2202. Maximize the Topmost Element After K Moves cover?
LeetCode 2202. Maximize the Topmost Element After K Moves is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview