leetcode-121 Best Time to Buy and Sell Stock
来源:互联网 发布:达内培训 大数据 编辑:程序博客网 时间:2024/05/23 02:07
只有一次交易的情况比较简单,就是最大减去最小,但是最小的值一定要出现在最大之前
<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution {public: int maxProfit(vector<int>& prices) { int len = prices.size(); if(len == 0) return 0; int min = prices[0]; int maxProfit = 0; for(int i = 1; i < len; i++){ int tmp = prices[i] - min; if(tmp > maxProfit) maxProfit = tmp; if(prices[i] < min) min = prices[i]; } return maxProfit; }};</span>
也有人用下面的方法:
用类似动态规划的思想,到第i天买入,那么我能赚到的最大利润是多少呢?就是i + 1 ~ n天中最大的股价减去第i天的。找最大股价的问题可以在找第i+1~n天的最大利润时顺便记录,
这样就得出了一个线性方法。
<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution {public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if (prices.size() == 0) return 0; int maxPrice = prices[prices.size()-1]; int ans = 0; for(int i = prices.size() - 1; i >= 0; i--) { maxPrice = max(maxPrice, prices[i]); ans = max(ans, maxPrice - prices[i]); } return ans; }};</span>
0 0
- LeetCode 121: Best Time to Buy and Sell Stock
- LeetCode(121)Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- LeetCode: Best Time to Buy and Sell Stock [121]
- LeetCode 121 Best Time to Buy and Sell Stock
- [leetcode 121] Best Time to Buy and Sell Stock
- Leetcode NO.121 Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- LeetCode(121) Best Time to Buy and Sell Stock (Java)
- leetcode-121 Best Time to Buy and Sell Stock
- leetcode || 121、Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock - LeetCode 121
- leetcode#121 Best Time to Buy and Sell Stock
- Leetcode 121 Best Time to Buy and Sell Stock
- Leetcode #121 Best Time to Buy and Sell Stock
- leetcode 121: Best Time to Buy and Sell Stock
- leetcode: (121) Best Time to Buy and Sell Stock
- 121 Best Time to Buy and Sell Stock [Leetcode]
- XML-Schema-01
- hdu 5212 Code (容斥)
- 第二章 逆序对 (思考题2.4)
- 前驱图和程序执行的关系
- 标准base64编码解码探究
- leetcode-121 Best Time to Buy and Sell Stock
- nginx配置
- 《More Effective C++ 35个改善编程与设计的有效方法》——第二章笔记
- Java异常(二) 《Effective Java》中关于异常处理的几条建议
- spring mvc的配置文件解析
- 了解指针(4)-- 指针和结构类型
- 统筹高效利用时间——《小强升职记(升级版):时间管理故事书》读后感
- 加密解密的介绍
- @property @synthesize