Problem Description
Given an array of integers, repeatedly construct a new array by taking pairs of numbers from the current array. For each pair, if the pair's index (in the new array) is even, insert the minimum of the two numbers; if odd, insert the maximum. Continue this process until only one number remains, and return that number.
Key Insights
- The array length is always a power of 2, which guarantees that it can be halved continuously.
- Use a simulation approach, iterating until the array is reduced to a single element.
- Depending on the index of the pair’s position in the new array, choose the minimum (for even indices) or maximum (for odd indices).
Space and Time Complexity
Time Complexity: O(n) per round, and with each round halving the array length, the overall time complexity is O(n). Space Complexity: O(n) in the worst case for creating the new array each round.
Solution
This problem can be solved by simulating the process described. The algorithm involves iteratively constructing a new array from the current array:
- Create a new array of half the length.
- For each pair (nums[2i], nums[2i+1]) in the current array:
- If the index i of the new array is even, set newNums[i] = min(nums[2i], nums[2i+1]).
- If i is odd, set newNums[i] = max(nums[2i], nums[2i+1]).
- Replace the current array with the new array.
- Repeat until only one element remains, then return that element.
The simulation approach is straightforward since the array length is a power of 2; thus, the pairing always works perfectly without edge cases.