[leetcode 122] Best Time to Buy and Sell Stock II
2016-01-13 22:56
393 查看
Quesiton:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time
(ie, you must sell the stock before you buy again).
分析:
知道每天股票的价钱,求可得到的最大利益。
首先要确定购买日期,在之后最高价日期卖掉。
代码如下:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time
(ie, you must sell the stock before you buy again).
分析:
知道每天股票的价钱,求可得到的最大利益。
首先要确定购买日期,在之后最高价日期卖掉。
代码如下:
<span style="font-size:14px;">class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size() < 2) return 0; int buy; int pro = 0; int i; buy = buyPos(prices,0); for(i = buy; i < prices.size()-1; ++i){ if(prices[i] > prices[i+1] && i != buy){ pro += (prices[i] - prices[buy]); buy = buyPos(prices,i+1); i = buy-1; } queding } if(i == prices.size()-1){ if(prices[i] > prices[buy]) pro += (prices[i] - prices[buy]); } return pro; } int buyPos(vector<int>& prices,int start){ int i = start; while(i != prices.size()-1 && prices[i] >= prices[i+1]) ++i; return i; } };</span>
相关文章推荐
- JDK的一些命令行工具
- [连载]《C#通讯(串口和网络)框架的设计与实现》- 12.二次开发及应用
- [连载]《C#通讯(串口和网络)框架的设计与实现》- 11.调试器的设计
- 在TextView周围添加图片
- CodeIgniter(CI 3.0)分页类实践记录
- Virtual DOM 虚拟DOM的理解(转)
- [连载]《C#通讯(串口和网络)框架的设计与实现》- 10.宿主程序详细设计
- Linux基础入门学习笔记一
- zabbix 客户端安装配置
- [连载]《C#通讯(串口和网络)框架的设计与实现》- 9.插件引擎设计
- tomcat集群基于redis共享session解决方案
- C#图片验证码,旋转文字主要代码
- 看<连城诀>有感
- [连载]《C#通讯(串口和网络)框架的设计与实现》- 8.总体控制器的设计
- django Meta 选项
- 认识Lucene(6):使用Lucene、LingPipe做实体链接(Entity Linking)——使用了LingPipe构建entity索引
- ES学习2
- [连载]《C#通讯(串口和网络)框架的设计与实现》- 7.外部接口的设计
- story
- [连载]《C#通讯(串口和网络)框架的设计与实现》- 6.通讯控制器的设计