Given a list of positive integers nums, you need to return a string that represents the optimal division of these numbers such that the value of the expression is maximized. In other words, you want to maximize the result of nums[0] / nums[1] / nums[2] / ... / nums[n-1].
Example 1:
nums = [1000, 100, 10, 2]"1000/(100/10/2)"1000/(100/10/2) = 1000/5 = 200, but 1000/100/10/2 = 0.5.Example 2:
nums = [2, 3, 4]"2/(3/4)"2/(3/4) = 2 * 4/3 = 8/3, but 2/3/4 = 1/6.Example 3:
nums = [2]"2"Your task is to return the optimal division as a string.
nums[0] / nums[1].nums or the value of its elements?
The key to maximize the result of division is to minimize the denominator resulting from the division.
nums[0] by a value that is as small as possible.nums = [a], output just a.nums = [a, b], output a/b.nums = [a, b, c, ...], output a/(b/c/...).def optimalDivision(nums):
if not nums:
return ""
# If there's only one number, just return that number
if len(nums) == 1:
return str(nums[0])
# If there are two numbers, just return the division of the two
if len(nums) == 2:
return f"{nums[0]}/{nums[1]}"
# For more than two numbers, encloses the rest of the numbers in parenthesis
result = '{}/({})'.format(nums[0], '/'.join(map(str, nums[1:])))
return result
# Test cases
print(optimalDivision([1000, 100, 10, 2])) # "1000/(100/10/2)"
print(optimalDivision([2, 3, 4])) # "2/(3/4)"
print(optimalDivision([2])) # "2"
print(optimalDivision([2, 3])) # "2/3"
The time complexity for this problem is O(n), where n is the length of the nums list. The most time-consuming operation is joining the strings with slashes, which is linear in the size of the list.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?