Skip to content

Commit

Permalink
added Best Time to Buy and Sell Stock
Browse files Browse the repository at this point in the history
  • Loading branch information
pezy committed Nov 22, 2014
1 parent 014c045 commit 723555c
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
11 changes: 11 additions & 0 deletions 39. Best Time to Buy and Sell Stock/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
今天和妹子去了天津,这道题的第一个版本就是在去天津的城铁上用手机提交的。其实 LeetCode 的移动web端已经做的很不错了,编辑器连括号都会自动补齐,而且还能补齐在合适的位置。语法高亮什么的就不必多说了,反正给我的体验很不错,只怪手机的屏幕太小,每次都提心吊胆是否会出现粗心的格式问题。

这道题很久之前做过它的第二版,也就是允许多次交易的,相比之下,只允许一次交易就显得非常简单了。本质还是那句,低买高卖。

由于在城铁上边聊天边做题,我写的很啰嗦,还弄了两个变量,一个low,一个high,迭代整个数组,遇到比high大的,将其赋值给high;如果遇到比low小的,在将其值赋给low的同时,还要注意将high也赋值为low,因为遇到更low的价格,意味着之前的 max profit 已经到了头,其high已经失去了意义,需要从头计算。当然很显然,整个过程中,max profit 要时刻保持最大值就是了。

这是所有求最大值最小值类型题的一个常用思路,留个变量在迭代过程中一直纪录max/min。

回家之后,发现其实high没有必要存在,因为如果low变化,high又要从新纪录,那么表明high其实是步步跟随prices迭代的脚步的,计算max的值时,与其让 high - low,还不如直接用 prices[i] - low。本质是没差别的。

于是在github上留下比较满意的这一版,希望大家指正。
10 changes: 10 additions & 0 deletions 39. Best Time to Buy and Sell Stock/main.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#include "solution.h"
#include <iostream>

int main()
{
Solution s;
std::vector<int> vec{2,4,3,7,9,2,5,6,10,1};
std::cout << s.maxProfit(vec) << std::endl;
return 0;
}
17 changes: 17 additions & 0 deletions 39. Best Time to Buy and Sell Stock/solution.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include <vector>
#include <algorithm>
using std::vector; using std::max; using std::min;

class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.empty()) return 0;
int ret{0}, low{prices[0]};
for (auto price : prices)
{
low = min(low, price);
ret = max(ret, price - low);
}
return ret;
}
};

0 comments on commit 723555c

Please sign in to comment.