[Leetcode] Best time to buy and sell stock 买卖股票的最佳时机
2017-06-29 16:05
465 查看
Say you have an array for which the i th 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.
题意:至多做一次买、卖,求利润的最大值。
思路:这个不是简单的求出数组的最大值和最小值,然后两者相减即可,因为,卖股票必须在买股票之前,也就是,较小值要在前。所以思路为:维护两个变量,一个是目前为止的最小值,一个是目前为止的利润。遍历数组,若当前值比最小值小,则更新最小值,若比最小值大则,计算其与最小值之间的差值是否大于当前最大利润,是,更新利润。代码如下:
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) 4 { 5 int minVal=prices[0]; 6 int profit=0; 7 8 for(int i=0;i<prices.size();++i) 9 { 10 minVal=min(prices[i],minVal); 11 profit=max(profit,prices[i]-minVal); 12 } 13 return profit; 14 } 15 };
相关文章推荐
- [Java语言] [Leetcode] Best Time to Buy and Sell Stock 买卖股票的最佳时机
- [Leetcode] Best time to buy and sell stock iii 买卖股票的最佳时机
- Leetcode121 Best Time to Buy and Sell Stock(买卖股票的最佳时机1)
- [Leetcode] Best time to buy and sell stock ii 买卖股票的最佳时机
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- [LeetCode 122] - 买入与卖出股票的最佳时机II(Best Time to Buy and Sell Stock II)
- [LeetCode 121] - 买入与卖出股票的最佳时机(Best Time to Buy and Sell Stock)
- 【LintCode】 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III
- **[Lintcode]Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV Leetcode
- [LeetCode] 188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时间 IV
- leetcode 121.Best Time to Buy and Sell Stock 股票买卖最佳时间
- 【LeetCode】Best Time to Buy and Sell Stock(买卖股票的最佳时间)
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
- LeetCode——Best Time to Buy and Sell Stock III (股票买卖时机问题3)
- Best Time to Buy and Sell Stock II 最佳时间买入卖出股票(多次买卖)@LeetCode
- LeetCode——Best Time to Buy and Sell Stock II (股票买卖时机问题2)
- LeetCode 121. Best Time to Buy and Sell Stock (买卖股票的最好时机)