553. Optimal Division

题目:给定一数组,相邻的整数执行除法,但是我们可以通过添加括号改变计算的优先级,求这组数字应该如何添加括号,从而得到的结果值最大,同时结果中不应该有多余的括号,以字符串形式返回结果。例子如下:

Input: [1000,100,10,2]
Output: "1000/(100/10/2)"
Explanation:
1000/(100/10/2) = 1000/((100/10)/2) = 200
However, the bold parenthesis in "1000/((100/10)/2)" are redundant, 
since they don't influence the operation priority. So you should return "1000/(100/10/2)". Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2)) = 50 1000/100/10/2 = 0.5 1000/100/(10/2) = 2

假设输入的数组为a,b,c,d。现在我们通过优先级设置来寻找a/b/c/d的最大值。我们知道要想p/q最大,q必须要最小。所在,b/c/d的值要最小。我们现在的目标是如何使b/c/d的值最小。现在有两种可能:b /(c / d)跟(b / c)/ d,可以得到:

b/(c/d)        (b/c)/d = b/c/d
(b*d)/c        b/(d*c)
d/c            1/(d*c)
显然d / c 大于 1 / (d * c),因为d大于1。所以我们只要保证越靠右的/的优先级最高就可以保证结果最大。代码如下:

class Solution {
public:
    string intToString(int n) {
        string temp;
        stringstream ss;
        ss << n;
        ss >> temp;
        return temp;
    }
    string optimalDivision(vector<int>& nums) {
        string result = "";
        if (nums.size() == 1) {
            result += intToString(nums[0]);
        } else if (nums.size() == 2) {
            result += (intToString(nums[0]) + "/" + intToString(nums[1]));
        } else {
            result += (intToString(nums[0]) + "/(" + intToString(nums[1]));
            for (int i = 2; i < nums.size(); i++) {
                result += ("/" + intToString(nums[i]));
            }
            result += ")";
        }
        return result;
    }
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值