[LeetCode] Maximize the Topmost Element After K Moves

2202. Maximize the Topmost Element After K Moves

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.
  • If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int maximumTop(vector<int>& nums, int k) {
if(nums.size() == 1) {
return k & 1 ? -1 : nums[0];
}
if(k == 1) return nums[1];

if(nums.size() >= k + 1) {
int ma = INT_MIN;
for(int i = 0; i < min((int)nums.size(), k + 1); i++) {
if(i == k - 1) continue;
ma = max(ma, nums[i]);
}
return ma;
} else if(nums.size() == k) {
int ma = INT_MIN;
for(int i = 0; i < nums.size() - 1; i++)
ma = max(ma, nums[i]);
return ma;
} else {
return *max_element(nums.begin(), nums.end());
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/13/PS/LeetCode/maximize-the-topmost-element-after-k-moves/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.