Leetcode_c++: Best Time to Buy and Sell Stock (121)
2016-06-10 23:15
483 查看
题目
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.
算法
O(n)时间,O(1)空间。动态规划法。从前向后遍历数组,记录当前出现过的最低价格,作为买入价格,并计算以当天价格出售的收益,作为可能的最大收益,整个遍历过程中,出现过的最大收益就是所求。
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size()<2) return 0; int maxprofile=0; int curmin=prices[0]; for(int i=1;i<prices.size();i++){ curmin=min(curmin,prices[i]); maxprofile=max(maxprofile,prices[i]-curmin); } return maxprofile; } };
相关文章推荐
- 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
- SCPPO(二):禅道的使用—管理员