Maximize the Topmost Element After K Moves LeetCode solution in JavaScript

1
var maximumTop = function (nums, k) {
2
const MIN = Number.MIN_SAFE_INTEGER;
3
const n = nums.length;
4

5
if (k === 0) return nums[0];
6
if (n === 1 && k % 2 == 1) return -1; // if there is only 1 item and k is odd, then the last move always will be removing the item
7
if (k === 1) return nums[1];
8
if (k > n) return Math.max(...nums);
9

10
let max = MIN;
11

12
for (let i = 1; i <= k - 1; ++i) {
13
const num = nums[i - 1];
14
max = Math.max(max, num);
15
}
16

17
if (k < n) return Math.max(max, nums[k]); // If there is 1 or more item than k in the array, then the two choices we have is to remove
18
// k elements which will make the nums[k] be the topmost element or removing k - 1 elements
19
// and putting the largest number from there back onto the pile.
20

21
return max;
22
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0