LeetCode-in-Java

2202. Maximize the Topmost Element After K Moves

Medium

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:

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:

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:

Solution

public class Solution {
    public int maximumTop(int[] nums, int k) {
        int max = -1;
        int maxTravers = Math.min(k + 1, nums.length);
        if (nums.length == 1) {
            if (k % 2 == 0) {
                return nums[0];
            } else {
                return max;
            }
        }
        for (int i = 0; i < maxTravers; i++) {
            if (nums[i] > max && i != k - 1) {
                max = nums[i];
            }
        }
        return max;
    }
}