• Time:O(n)
• Space:O(n)

## C++

``````class Solution {
public:
string optimalDivision(vector<int>& 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;
}
};
``````

## JAVA

``````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();
}
}
``````

## Python

``````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
``````