博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode-553-Optimal Division]
阅读量:7046 次
发布时间:2019-06-28

本文共 1875 字,大约阅读时间需要 6 分钟。

Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4.

However, you can add any number of parenthesis at any position to change the priority of operations.
You should find out how to add parenthesis to get the maximum result,
and return the corresponding expression in string format. Your expression should NOT contain redundant parenthesis.
Example:
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
Note:
The length of the input array is [1, 10].
Elements in the given array will be in range [2, 1000].
There is only one optimal division for each test case.

思路:

大牛原话:

“X1/X2/X3/../Xn will always be equal to (X1/X2) * Y,no matter how you place parentheses.

i.e no matter how you place parentheses, X1 always goes to the numerator and X2 always goes to the denominator.

Hence you just need to maximize Y. And Y is maximized when it is equal to X3 *..*Xn.

So the answer is always X1/(X2/X3/../Xn) = (X1 *X3 *..*Xn)/X2

有了这个结果其实就简单了。。。重要的是过程,要想得到最大结果,那么第一个数字X1一定是作为分子,第二个数X2一定是作为分母。

于是就有了X1/(X2/X3/../Xn) 。

string optimalDivision(vector
& nums) { string ret; ret = to_string(nums[0]); if (nums.size() == 1)return ret; if (nums.size() == 2) return ret + "/" + to_string(nums[1]); ret += "/(" + to_string(nums[1]); for (int i = 2; i < nums.size();i++) { ret += "/" + to_string(nums[i]); } ret += ")"; return ret; }

 

参考:

转载于:https://www.cnblogs.com/hellowooorld/p/6807513.html

你可能感兴趣的文章
yaf插件类的使用
查看>>
SSD内部的IO抖动因素
查看>>
Skype for Business Server 2015-04-前端服务器-4-准备Active Directory
查看>>
PHP流程控制的替代语法
查看>>
完全解析H3C路由器动态NAT配置步骤
查看>>
天涯的运维之路
查看>>
运维人员低学历者要不要补学历?何时补合适?
查看>>
【原创】日志表设计一例分析
查看>>
nmcli网卡绑定与teaming配置
查看>>
为什么还是穷人:工作的态度
查看>>
Provisioning Services 7.8 入门系列教程之三 安装并配置 Provisioning Services
查看>>
RHEL6基础三十之服务器维护基础命令①netstat
查看>>
Puppet 实验十 centos 安装 puppet-dashboard 仪表盘
查看>>
SQL Server 2017 AlwaysOn on Linux 配置和维护(11)
查看>>
C#基础知识整理:基础知识(7) 方法的隐藏
查看>>
SQL Server可以锁定的资源类型
查看>>
基于VMware vSphere 5.0的服务器虚拟化实践(3)
查看>>
Linux系统负载均衡软件之haproxy+apache
查看>>
风险评估 Risk Assessment
查看>>
Cent OS 6.4 虚拟机安装实践(一)基本安装
查看>>