Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
You are given a 0-indexed integer array nums
whose length is a power of 2
.
Apply the following algorithm on nums
:
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
after applying the algorithm.
Example 1:
Input: nums = [1,3,5,2,4,8,2,2]
Output: 1
Explanation: The following arrays are the results of applying the algorithm repeatedly.
First: nums = [1,5,4,2]
Second: nums = [1,4]
Third: nums = [1]
1 is the last remaining number, so we return 1.
Example 2:
Input: nums = [3]
Output: 3
Explanation: 3 is already the last remaining number, so we return 3.
Constraints:
1 <= nums.length <= 1024
1 <= nums[i] <= 109
nums.length
is a power of 2
.#base case
if len(nums)==1:
return nums[0]
#as long as my length doesn't become 1, I repeat the process
while len(nums)!=1:
#we take a newnums everytime of size n//2
newnums = [-1]*(len(nums)//2)
for i in range(0,len(nums)//2):
if i%2==0:
newnums[i] = min(nums[2 * i], nums[2 * i + 1])
else:
newnums[i] = max(nums[2 * i], nums[2 * i + 1])
#add the newarray to the older one.
nums = newnums
return nums[0]
public int minMaxGame(int[] nums) {
List<Integer> list = new ArrayList<>();
for(int i:nums) list.add(i);
while(list.size()!=1){
List<Integer> dummy = new ArrayList<>();
boolean f = true;
for(int i=1;i<list.size();i+=2){
if(f) dummy.add(Math.min(list.get(i-1),list.get(i)));
else dummy.add(Math.max(list.get(i-1),list.get(i)));
f = f ^ true;
}
list = dummy;
}
return list.get(0);
}
class Solution {
vector<int> helper(vector<int>& nums,int n){
vector<int> ans;
for(int i=0;i<n/2;i++){
if(i%2 == 0) ans.emplace_back(min(nums[2*i],nums[2*i+1]));
else ans.emplace_back(max(nums[2 * i], nums[2 * i + 1]));
}
return ans;
}
public:
int minMaxGame(vector<int>& nums) {
int n=size(nums);
if(n == 1) return nums[0];
while(true){
vector<int> arr = helper(nums,n);
n = arr.size();
nums = arr;
if(n == 1) return arr[0];
}
return 0;
}
};
In our experience, we suggest you solve this Min Max Game LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Min Max Game LeetCode Solution
I hope this Min Max Game LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>