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.
1#include <iostream>
2#include <string>
3#include <vector>
4#include <sstream>
5
6using namespace std;
7
8string optimalDivision(vector<int>& nums) {
9 if (nums.size() == 1) return to_string(nums[0]);
10 if (nums.size() == 2) return to_string(nums[0]) + "/" + to_string(nums[1]);
11 ostringstream result;
12 result << nums[0] << "/(";
13 for (size_t i = 1; i < nums.size(); ++i) {
14 result << nums[i];
15 if (i != nums.size() - 1) result << "/";
16 }
17 result << ")";
18 return result.str();
19}
The C++ solution uses string streams for string manipulation, making it efficient for concatenating numbers and symbols. It handles small cases directly and builds the resulting string using a loop to ensure correct operator placement and enclosing parentheses.