博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【一天一道LeetCode】#121. Best Time to Buy and Sell Stock
阅读量:4197 次
发布时间:2019-05-26

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

#

一天一道LeetCode

本系列文章已全部上传至我的github,地址:

欢迎大家关注我的新浪微博,
欢迎转载,转载请注明出处

(一)题目

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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]

Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]

Output: 0
In this case, no transaction is done, i.e. max profit = 0.

(二)解题

题目大意:给定一个数组表示一天之内的股价变化,只有一次买卖机会,如何做到利润最大。

解题思路:考虑采用两个指针i和j以及一个maxpro,第i时刻买,第j时刻卖(i

class Solution {public:    int maxProfit(vector
& prices) { int n = prices.size(); int maxpro = 0;//表示最大利润 int i = 0;//第i时刻买 for(int j = 1 ; j < n ; j++) { if(prices[j]>prices[i]){
//当大于买时的价钱时 int temp = prices[j] - prices[i];//计算利润 maxpro = max(maxpro,temp);//更改maxpro,保存最大利润值 } else { i=j;//新的买时刻 } } return maxpro;//返回最大利润 }};
你可能感兴趣的文章
mongodb group 有条件的过滤组合个数。
查看>>
yii2 用命令行操作web下的controller
查看>>
yii2 console的使用
查看>>
关于mongodb的 数组分组 array group
查看>>
MongoDB新的数据统计框架介绍
查看>>
mongodb fulltextsearch 关于语言的设置选项
查看>>
mongodb 增加全文检索索引
查看>>
symfony
查看>>
yourls 短连接 安装
查看>>
yii2 php namespace 引入第三方非namespace库文件时候,报错:Class not found 的解决
查看>>
softlayer 端口开放
查看>>
操作1:mongodb安装
查看>>
操作2:mongodb使用语法
查看>>
如何给分类增加一个属性(后台)
查看>>
linux设置环境变量 临时设置 和 永久设置
查看>>
检查网站在世界各地的打开速度
查看>>
jquery 向上(顶部),向下(底部)滑动
查看>>
seo
查看>>
10个出色的NoSQL数据库
查看>>
MySQL: InnoDB 还是 MyISAM?
查看>>