MediumNo. 2202

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

Pattern
Greedy
Topics
Greedy, Array
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

PythonSolution
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

Time
O(n log n)
Space · auxiliary
O(1) to O(n)

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

Related problems
No.ProblemDifficulty
2208Minimum Operations to Halve Array SumMedium
2195Append K Integers With Minimal SumMedium
0011Container With Most WaterMedium
0134Gas StationMedium
0135CandyHard
0179Largest NumberMedium

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.

Free to download. Check it runs on your machine, then pick a plan.