博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Best Time to Buy and Sell Stock
阅读量:4071 次
发布时间:2019-05-25

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

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

解析:在给定的数组中,求最大值和最小值的差值即为所得。要求是这里的最大值在最小值的后面出现。一般而言,我们处理问题总是习惯从前向后处理,这个题目中从后向前处理显的更符合逻辑。在现实中,我们买了股票总是处于观望状态,总是期望价钱越来越高,即使出现短期的回落,我们也总是希望并相信未来会上扬。从另一个角度来说,我们从当前去看未来总是感觉扑朔迷离,但是当前看过去却看得分外清晰。

所以我们从交易的最后一天作出售开始(再不卖交易截止了,废了),我们开始向前去找,找到比出售这天价钱低的,我们求一下此时的利润,要是比当前的最大利润要高,我们更改最大值,并继续向前找,因为我们总是希望并相信还有更低的买进价格,直到走到开盘那天(下标0),若这其中遇到比出售的价格高的情况,我们就将当前遇到的这个高的价格作为出售价格,继续以上的操作,最后获得最大利润。

class Solution {public:    int maxProfit(vector
&stock) { int sell = stock.size() - 1; int max_profit = 0; for(; sell >= 0; ){ int buy = sell - 1; int cur_profit = 0; int cur_pay = 0; while (buy >= 0 && stock[buy] < stock[sell]) { cur_profit = stock[sell] - stock[buy--]; if(cur_profit > max_profit) max_profit = cur_profit; } sell = buy; } return max_profit; }};

转载地址:http://zglji.baihongyu.com/

你可能感兴趣的文章
更改 ceph journal 位置
查看>>
docker private registry using rados beckend
查看>>
使用 docker 后出现的网络异常现象
查看>>
ceph ( requests are blocked ) 异常解决方法
查看>>
ceph 报警 [ low disk space] 解决
查看>>
python 调用 lvs 脚本 [备忘]
查看>>
openstack 命令行管理二十一 - 云盘管理 (备忘)
查看>>
docker 文件位置[备忘]
查看>>
rhel7 kickstart 参考[备忘]
查看>>
DNS请求分析
查看>>
docker - 资源限制
查看>>
puppet 配置 1. 服务器, 客户端配置说明
查看>>
puppet 配置 2 模块
查看>>
puppet 配置 3. 资源
查看>>
打造自己的 DockerImage
查看>>
rhel7.2 优化技巧
查看>>
megacli 划分, 删除 raid 方法备忘
查看>>
ceph - crush map 与 pool
查看>>
openstack 管理二十二 - cinder 连接多个存储 backend
查看>>
puppet 配置 3.1 管理 sysct.conf
查看>>