Math Solution C++ with explanation


  • 0
    Z

    a2 must be divided by a1 wherever we put parenthesis (may be divided by a1 a little later).

    the best choice is a1 / (a2 / ... / an ) = (a1 * a3 * ... * an) / a2
    only a2 need to be divided.

    • input : a1 / a2 / ... / an
    • output : a1 / (a2 / ... / an )
    class Solution {
    public:
        string optimalDivision(vector<int>& nums) {
            string ans;
            int len = 0;
            for(int i = 0; i != nums.size(); ++ i){
                if(i > 0) ans += "/";
                if(i == 1 && nums.size() > 2) ans += "(";
                ans += to_string(nums[i]);
                if(i == nums.size() - 1 && nums.size() > 2) ans += ")";
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.