In this problem, you are given a 0-indexed integer array nums
whose length is a power of 2.
Apply the following algorithm on nums
repeatedly until the length of nums
becomes 1:
newNums
of length nums.length / 2
.i
where 0 <= i < nums.length / 2
, assign the value of newNums[i]
as:
newNums[i] = min(nums[2 * i], nums[2 * i + 1])
if i
is even.newNums[i] = max(nums[2 * i], nums[2 * i + 1])
if i
is odd.nums
with newNums
.Return the last number that remains in nums
.
nums
contain negative numbers or is it only non-negative integers?nums
array?Clarifications:
nums
can contain negative numbers.nums
is guaranteed to be a power of 2, but no specific upper limit is provided.nums
.Let’s proceed to implement this in Python.
def minMaxGame(nums):
while len(nums) > 1:
newNums = []
for i in range(len(nums) // 2):
if i % 2 == 0:
newNums.append(min(nums[2 * i], nums[2 * i + 1]))
else:
newNums.append(max(nums[2 * i], nums[2 * i + 1]))
nums = newNums
return nums[0]
# Test the function with an example input
print(minMaxGame([1, 3, 5, 2, 4, 8, 2, 2])) # Expected output depends on the input sequence.
nums
.newNums
at each iteration.nums
:
nums
with newNums
.nums
becomes 1, return the single element in nums
.nums
.Thus, the overall time complexity is O(n log n).
This approach effectively reduces the problem size at each step, ensuring efficient execution even for larger inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?