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.
1public class Solution {
2 public String optimalDivision(int[] nums) {
3 if (nums.length == 1) return String.valueOf(nums[0]);
4 if (nums.length == 2) return nums[0] + "/" + nums[1];
5 StringBuilder result = new StringBuilder();
6 result.append(nums[0]).append("/(");
7 for (int i = 1; i < nums.length; i++) {
8 result.append(nums[i]);
9 if (i != nums.length - 1) result.append("/");
10 }
11 result.append(")");
12 return result.toString();
13 }
14}
The Java solution uses a StringBuilder for efficient string manipulation, handling base cases for inputs of size 1 or 2 with simple returns. For larger arrays, it constructs the optimal division expression using a loop that appends numbers and symbols appropriately, enclosing the division sequence in parentheses.