Leetcode problem 2293: Min Max Game
You are given an integer array nums
. Our goal is to repeatedly perform the following operation until we have only one number left in the array:
newNums
.i
in the range of 0
to [n/2 - 1]
, where n
is the current length of nums
, replace newNums[i]
with:
min(nums[2 * i], nums[2 * i + 1])
if i
is even.max(nums[2 * i], nums[2 * i + 1])
if i
is odd.Return the only number left in the array after performing the operations repeatedly.
nums
.newNums
from nums
until the array length becomes 1.nums
array to build the newNums
array.newNums
.nums
with newNums
and repeat until a single element remains.#include <vector>
#include <algorithm>
int minMaxGame(std::vector<int>& nums) {
while (nums.size() > 1) {
std::vector<int> newNums(nums.size() / 2);
for (int i = 0; i < newNums.size(); ++i) {
if (i % 2 == 0) {
newNums[i] = std::min(nums[2 * i], nums[2 * i + 1]);
} else {
newNums[i] = std::max(nums[2 * i], nums[2 * i + 1]);
}
}
nums = newNums;
}
return nums[0];
}
nums
is halved, resulting in ((n/2, n/4, …, 1)).Combining these, the overall time complexity is:
[ O(n) \text{ work per iteration} \times O(\log n) \text{ iterations} = O(n \log n) ]
This approach ensures efficient handling of the problem within the constraints.
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?