# 553. Optimal Division

• Time: $O(n)$
• Space: $O(n)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution { public: string optimalDivision(vector& nums) { string ans = to_string(nums[0]); if (nums.size() == 1) return ans; if (nums.size() == 2) return ans + "/" + to_string(nums[1]); ans += "/(" + to_string(nums[1]); for (int i = 2; i < nums.size(); ++i) ans += "/" + to_string(nums[i]); ans += ")"; return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public String optimalDivision(int[] nums) { StringBuilder sb = new StringBuilder(String.valueOf(nums[0])); if (nums.length == 1) return sb.toString(); if (nums.length == 2) return sb.append('/').append(nums[1]).toString(); sb.append("/(").append(nums[1]); for (int i = 2; i < nums.length; ++i) sb.append('/').append(nums[i]); sb.append(')'); return sb.toString(); } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution: def optimalDivision(self, nums: List[int]) -> str: ans = str(nums[0]) if len(nums) == 1: return ans if len(nums) == 2: return ans + '/' + str(nums[1]) ans += '/(' + str(nums[1]) for i in range(2, len(nums)): ans += '/' + str(nums[i]) ans += ')' return ans