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.
1function optimalDivision(nums) {
2 if (nums.length === 1) return nums[0].toString();
3 if (nums.length === 2) return nums[0] + '/' + nums[1];
4 return nums[0] + '/(' + nums.slice(1).join('/') + ')';
5}
Similar to the Python approach, we handle cases for 1 and 2 numbers separately. For longer arrays, we form the division expression by slicing out the rest of the numbers except the first and joining them with division operators, enclosed in parentheses.