Maximize the Topmost Element After K Moves

medium array greedy

Problem

You are given a 0-indexed array nums that represents a pile, where index 0 is the topmost element. You are also given an integer k. You must make exactly k moves. On each move you either remove the current topmost element, or add back to the top one element you removed on an earlier move. Return the largest value that can be sitting on top after exactly k moves, or -1 if no element can be on top.

Inputnums = [5, 2, 2, 4, 0, 6], k = 4
Output5
Remove the first 3 elements (5, 2, 2), then on the 4th move add 5 back to the top. The best reachable values are the largest of nums[0..k-2] = max(5, 2, 2) = 5, versus nums[k] = nums[4] = 0; the winner is 5.

def maximum_top(nums, k):
    n = len(nums)
    if n == 1:
        return -1 if k % 2 == 1 else nums[0]
    best = -1
    for i in range(min(k - 1, n)):
        best = max(best, nums[i])
    if k < n:
        best = max(best, nums[k])
    return best
function maximumTop(nums, k) {
  const n = nums.length;
  if (n === 1) {
    return k % 2 === 1 ? -1 : nums[0];
  }
  let best = -1;
  for (let i = 0; i < Math.min(k - 1, n); i++) {
    best = Math.max(best, nums[i]);
  }
  if (k < n) {
    best = Math.max(best, nums[k]);
  }
  return best;
}
class Solution {
    public int maximumTop(int[] nums, int k) {
        int n = nums.length;
        if (n == 1) {
            return k % 2 == 1 ? -1 : nums[0];
        }
        int best = -1;
        for (int i = 0; i < Math.min(k - 1, n); i++) {
            best = Math.max(best, nums[i]);
        }
        if (k < n) {
            best = Math.max(best, nums[k]);
        }
        return best;
    }
}
int maximumTop(vector<int>& nums, int k) {
    int n = (int)nums.size();
    if (n == 1) {
        return k % 2 == 1 ? -1 : nums[0];
    }
    int best = -1;
    for (int i = 0; i < min(k - 1, n); i++) {
        best = max(best, nums[i]);
    }
    if (k < n) {
        best = max(best, nums[k]);
    }
    return best;
}
Time: O(min(k, n)) Space: O(1)