122. Best Time to Buy and Sell Stock II (Array)
2015-10-14 18:45
393 查看
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).
法I:从左向右扫描,找到每个递增序列的第一个元素和最后一个元素
法II:递增就就算profit
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).
法I:从左向右扫描,找到每个递增序列的第一个元素和最后一个元素
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.empty()) return 0; if(prices.size() == 1) return 0; int maxProfit = 0; int buyPrice = 0; int prePrice; bool asc = false; //if in ascending sequence vector<int>::iterator it= prices.begin(); prePrice = *it; it++; for(; it < prices.end(); it++) { if ((*it)>prePrice) { if(!asc) //find the first element in the ascending sequence { buyPrice = prePrice; asc = true; } } else if ((*it)< prePrice) { if(asc) //find the last element in the ascending sequence { maxProfit = prePrice - buyPrice + maxProfit; asc = false; } } prePrice = *it; } if(asc) { maxProfit = prePrice - buyPrice + maxProfit; } return maxProfit; } };
法II:递增就就算profit
class Solution { public: int maxProfit(vector<int>& prices) { int profit = 0; for (int i=0; i<(int)prices.size()-1; i++) { if (prices[i+1] > prices[i]) profit += prices[i+1] - prices[i]; } return profit; } };
相关文章推荐
- git submodule子模块
- 第六章 存储器层次结构
- 远程数据client交换器
- 第七周 项目2 建立链队算法库
- framework的native文件夹下的cpp文件里使用property的过程
- Jquery中$.ajax $.post load用法与区别
- Android属性动画之ValueAnimator
- java线程池
- 距离详解Linux下的UDP方式通讯
- android中EditText有光标不弹出软键盘处理(转)
- python脚本控制鼠标和键盘-实例
- 集合 --- ArrayList
- Linux下lzop命令安装
- java调用html模板发送html内容的邮件
- STL之map/multimap关联式容器学习
- JavaScript中字体浮动的简单演示实例
- 【转载】 Visual Studio插入自定义代码段
- 数据库-关系代数-对除法的理解
- Java线程面试题 Top 50
- git使用总结