121. Best Time to Buy and Sell Stock
2016-05-02 15:13
316 查看
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.
题意:根据股票每天的价格,找出最佳的买卖点,使得股票收益最大。
思路:动态规划,f(n) = max(f(n-1), a
-min(a[1,n-1]));
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.
题意:根据股票每天的价格,找出最佳的买卖点,使得股票收益最大。
思路:动态规划,f(n) = max(f(n-1), a
-min(a[1,n-1]));
class Solution { public: int maxProfit(vector<int>& prices) { int size = prices.size(); if(size < 2) return 0; vector<int> f(size, 0); f[0] = 0; f[1] = max(0, prices[1] - prices[0]); int min = prices[0]; if (prices[1] < min) min = prices[1]; for (int i = 2; i < size; i++){ f[i] = max(f[i - 1], prices[i] - min); if (prices[i] < min) min = prices[i]; } return f[size - 1]; } };
相关文章推荐
- 解决Setting property 'source' to 'org.eclipse.jst.jee.server的问题
- Java集合(2)——深入理解ArrayList、Vector和LinkedList
- 实验7 BindService模拟通信
- top-k-frequent-elements
- visual studio 2013设置字体
- nfs部署和优化
- hdu 3461 Code Lock【并查集+快速幂】
- vmware下CentOS的host-only连接
- PHP中 HTTP_HOST 和 SERVER_NAME 的区别
- PySide学习笔记第十二章-绘制
- 接口回调
- 二叉树 - 小球下落简化解法
- Mac 文字编辑快捷键
- POJ 2105 IP Address(简单模拟)
- 数据可视化的实现技术和工具比较(HTML5 canvas(Echart)、SVG、webGL等等)
- 2、内核基本学习
- 洛谷P1803凌乱的yyy
- Emacs快速指南摘要
- 【平衡树】splay
- Haar特征的另一种的快速计算方法—boxfilter