You are given a 0-indexed integer array nums whose length is a power of 2.
Apply the following algorithm repeatedly until there is only one element remaining:
n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2.i where 0 <= i < n / 2, assign the value of newNums[i] as min(nums[2 * i], nums[2 * i + 1]).i where 0 <= i < n / 2, assign the value of newNums[i] as max(nums[2 * i], nums[2 * i + 1]).nums with newNums.Return the last number that remains in nums.
nums?
A: The length of the array will always be a power of 2, and within a reasonable range for typical array operations.nums be negative?
A: Yes, the elements of nums can be any integers, both negative and positive.newNums, how should we handle an element if i is neither even nor odd?
A: Each index i will always be either even or odd by definition of integers.nums is 1, return nums[0].newNums array.
newNums, take the minimum of the corresponding two elements from nums.newNums, take the maximum of the corresponding two elements from nums.nums with newNums and repeat until nums has only one element.class Solution {
public int minMaxGame(int[] nums) {
while (nums.length > 1) {
int n = nums.length;
int[] newNums = new int[n / 2];
for (int i = 0; i < n / 2; i++) {
if (i % 2 == 0) {
newNums[i] = Math.min(nums[2 * i], nums[2 * i + 1]);
} else {
newNums[i] = Math.max(nums[2 * i], nums[2 * i + 1]);
}
}
nums = newNums;
}
return nums[0];
}
}
The time complexity of this algorithm is O(n), where n is the length of the initial nums array:
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?