Maximum Possible Number by Binary Concatenation Problem
#3309
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3309.
You are given an array of integers nums of size 3.
Return the maximum possible number whose binary representation can be formed by concatenating the binary representation of all elements in nums in some order.
Note that the binary representation of any number does not contain leading zeros.
Example 1:
Input: nums = [1,2,3]
Output: 30
Explanation:
Concatenate the numbers in the order [3, 1, 2] to get the result "11110", which is the binary representation of 30.
Example 2:
Input: nums = [2,8,16]
Output: 1296
Explanation:
Concatenate the numbers in the order [2, 8, 16] to get the result "10100010000", which is the binary representation of 1296.
Constraints:
nums.length == 31 <= nums[i] <= 127
Solution
Approach: Enumeration
There are only three numbers, so try all 3! = 6 orders. For each order, write the numbers in binary, concatenate the strings, and read the result as a binary number. The largest of the six values is the answer.
Complexity: O(log M) time and O(1) space, where M is the largest value in nums.
from itertools import permutations
class Solution:
def maxGoodNumber(self, nums: List[int]) -> int:
ans = 0
for arr in permutations(nums):
num = int("".join(bin(i)[2:] for i in arr), 2)
ans = max(ans, num)
return ans