Sponsored
Sponsored
The key observation is that to maximize the result of the division, we should minimize the denominator. We achieve this by grouping as many elements as possible in the denominator so that the result becomes maximum. Hence, we should divide the first number by all the numbers after the first number treated as one single division.
Time Complexity: O(n), where n is the number of elements in nums. We iterate through the nums once to construct the string.
Space Complexity: O(n), for storing the joined string.
1def optimalDivision(nums):
2 if len(nums) == 1:
3 return str(nums[0])
4 if len(nums) == 2:
5 return f"{nums[0]}/{nums[1]}"
6 return f"{nums[0]}/({"/".join(map(str, nums[1:]))})"
The solution starts by checking if the length of the array is 1 or 2. For these cases, the return is straightforward as no extra parentheses are needed. For more than two numbers, the first number is divided by the expression of the rest, enclosed in parentheses to ensure that division occurs from left to right within the parentheses, thus maximizing the result.