#2202

Maximize the Topmost Element After K Moves

Medium
ArrayGreedyGreedyArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach leverages the fact that we only need to consider elements that can potentially be the topmost after k moves. We check the first k elements and the last element if k is less than the length of nums.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to track the maximum top element found.
  2. 2Step 2: Loop through the first min(k, len(nums)) elements and update the maximum.
  3. 3Step 3: If k is greater than or equal to the length of nums, also consider the last element in nums.
  4. 4Step 4: Return the maximum found or -1 if no valid topmost element exists.
solution.py11 lines
1# Full working Python code
2
3def maxTop(nums, k):
4    max_top = -1
5    limit = min(k, len(nums))
6    for i in range(limit):
7        max_top = max(max_top, nums[i])
8    if k >= len(nums):
9        max_top = max(max_top, nums[-1])
10    return max_top if max_top != -1 else -1
11

Complexity note: The time complexity is O(n) because we only loop through the first k elements and possibly the last element. The space complexity is O(1) as we only use a few variables.

  • 1You can only consider elements that are within the first k moves or the last element if k is larger than the number of elements.
  • 2If k is less than the length of nums, you cannot add back any removed elements beyond the first k.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.