[LeetCode] Min Max Game

2293. Min Max Game

You are given a 0-indexed integer array nums whose length is a power of 2.

Apply the following algorithm on nums:

  1. Let 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.
  2. For every even index i where 0 <= i < n / 2, assign the value of newNums[i] as min(nums[2 i], nums[2 i + 1]).
  3. For every odd index i where 0 <= i < n / 2, assign the value of newNums[i] as max(nums[2 i], nums[2 i + 1]).
  4. Replace the array nums with newNums.
  5. Repeat the entire process starting from step 1.

Return the last number that remains in nums after applying the algorithm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int minMaxGame(vector<int>& nums) {
while(nums.size() > 1) {
vector<int> A;
int n = nums.size();
bool mi = true;
for(int i = 0; i < n; i += 2, mi = !mi) {
if(mi) {
A.push_back(min(nums[i], nums[i + 1]));
} else {
A.push_back(max(nums[i], nums[i + 1]));
}
}
swap(nums, A);
}
return nums[0];
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/05/PS/LeetCode/min-max-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.