Best Time to Buy and Sell Stock II
来源:互联网 发布:网络引导安装系统 编辑:程序博客网 时间:2024/05/29 18:25
Best Time to Buy and Sell Stock II
题目:给你一个vector表示某个时间段内的股价情况。你可以任意买卖。但是只有卖掉股票后才能再买。求这段期间内,你能从股市中获得的最大收益。
解决:在局部最小值买入,局部最大值卖出。用到贪心算法。这个问题乍一看很复杂。很难同时求最小和最大。
实质是:
若今天价格比昨天低,则认为昨日为局部最大值。该在昨日卖出股票,今日买入,否则继续持有观望。
有意思的是,若股票呈现下降趋势,则程序会不断更新买入价,从而找到局部最小值。
class Solution {public: int maxProfit(vector<int> &prices) { int m = prices.size(); if(m == 0) return 0; int ret = 0; //利润 int buy = prices[0]; //买入价 int last = prices[0]; //昨天报价 for(int i = 1; i < m; i ++) { if(prices[i] < last) //今日比昨日便宜,说明昨天是局部最大值。 { ret += (last - buy); buy = prices[i]; } last = prices[i]; } ret += (last - buy); //这是个关键点,因为如果股票一直涨,则该认为边界点就是局部最大值 return ret; }};
0 0
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [LeetCode] Best time to buy and sell a stock II
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- LeetCode - Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- HttpClient 四种请求访问代码 HttpGet HttpPost HttpPut HttpDelete
- ubuntu14.04添加ia32-libs安装32位软件
- IllegalStateException: Recursive entry to executePendingTransactions
- MySQL Workbench建表时 PK NN UQ BIN UN ZF AI Default 的含义
- 一起talk C栗子吧(第一百三十八回:C语言实例--文件操作:基于文件描述符一)
- Best Time to Buy and Sell Stock II
- ip地址切换批处理脚本
- HTML 表格
- extjs2下拉树选项框comboxWithTree(支持异步加载子节点)
- 【转】小波变换通俗解释
- Java 中泛型的协变
- C#中Internal关键字的总结
- ubuntu 14.04 java开发环境搭建 jdk 以及 inteliJ IDEA安装
- 如何使用gson解析泛型形参并返回相对应的类