LEETCODE: Best Time to Buy and Sell Stock
来源:互联网 发布:监控视频显示无网络 编辑:程序博客网 时间:2024/06/08 14:24
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.
class Solution {public: int maxProfit(vector<int> &prices) { vector<int> maxs(prices.size()); vector<int> mins(prices.size()); // Get min from left to right at what time we may buy. for(int ii = 0; ii < prices.size(); ii ++) { if(ii == 0) { mins[ii] = prices[ii]; } else { mins[ii] = min(mins[ii - 1], prices[ii]); } } // Get max from right to left at what time we may sell. for(int ii = prices.size() - 1; ii >= 0; ii --) { if(ii == prices.size() - 1) { maxs[ii] = prices[ii]; } else { maxs[ii] = max(maxs[ii + 1], prices[ii]); } } int maxgap = 0; for(int ii = 0; ii < maxs.size(); ii ++) { if(maxgap < maxs[ii] - mins[ii]) { maxgap = maxs[ii] - mins[ii]; } } return maxgap; }};
0 0
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- Unity NGUI学习
- 联想thinkpad E431 win8重装win7系统步骤
- Spring P标签的使用
- JPA EntityManager详解(二)
- layoutSubviews总结
- LEETCODE: Best Time to Buy and Sell Stock
- 匆匆那年,纪念我的2014
- 关于UILabel的一点使用心得
- 【USACO 2008 Open Gold】 2.Crisis on the Farm 动规、
- UVA 10163 Storage Keepers (01背包DP + 二分)
- 3d 鱼的旋转角度
- Java基础----DataInputStream、DataOutputStream
- 公司新产品之我见(4)——便携式蔬果检测仪
- jpa nativeQuery