leetcode_c++:Best Time to Buy and Sell Stock II(122)
2016-06-10 23:19
525 查看
题目
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个数表示股票在第i天的价格。交易次数不限,但一次只能交易一支股票,也就是说手上最多只能持有一支股票,求最大收益。分析:贪心法。从前向后遍历数组,只要当天的价格高于前一天的价格,就算入收益。
代码:时间O(n),空间O(1)。
此题和上面一题的不同之处在于不限制交易次数。也是一次遍历即可,只要可以赚就做交易。
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size()<2) return 0; int maxprofile=0; for(int i=1;i<prices.size();i++){ int diff=prices[i]-prices[i-1]; if(diff>0) maxprofile+=diff; } return maxprofile; } };
相关文章推荐
- Leetcode_c++: Best Time to Buy and Sell Stock (121)
- Binary Tree Level Order Traversal II
- c++:角色类
- C++入门之一【类:析构函数)】
- Leetcode_c++: Triangle (120)
- c语言:递归求最大公约数
- VC++6.0玩OpenGL(一)
- Leetcode_c++: Pascal's TriangleII (119)
- C++操作符函数
- 找出字符串中的所有数字字符串(C/C++实现)
- Leetcode_c++: Pascal's Triangle(118)
- C++中的const用法
- Leetcode_c++:Construct Binary Tree from Inorder and Postorder Traversal (106)
- SCPPO(三):禅道的使用—项目管理员、开发等人员
- 指针和引用
- win7旗舰版安装VC++6.0番茄插件和行号显示
- C++ 删除指定路径文件夹
- C语言选择排序详解及其实现
- C++解压zip文件
- C++11中的std::bind