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 nums[0].ToString();
4 if (nums.Length == 2) return nums[0] + "/" + nums[1];
5 var result = new System.Text.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}
In C#, a StringBuilder is utilized to efficiently construct the division expression. Base cases handle inputs of length 1 and 2 directly, while a loop is used for longer arrays to append the string result properly, ensuring maximum division result through strategic parenthesizing.