leetcode 121. 买卖股票的最佳时机
2019-03-20 10:35
204 查看
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
最早考虑的是两个for循环嵌套发现超时,时间复杂度是O(n**2),看到别人的方法恍然大悟,设一个最小值的记录 和一个最大收益的记录即可。
python3实现
class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 min_num = prices[0] max_profit = 0 for i in prices: if i<min_num: min_num = i elif i - min_num > max_profit: max_profit = i - min_num return max_profit
C++实现
class Solution { public: int maxProfit(vector<int>& prices) { int min_num = INT_MAX; int max_profit = 0; if(prices.empty()) return 0; for (int i:prices){ if(i<min_num) min_num = i; else if(i-min_num >max_profit) max_profit = i-min_num; } return max_profit; } };
相关文章推荐
- Leetcode 121. 买卖股票的最佳时机
- LeetCode 121. 买卖股票的最佳时机
- LeetCode 121. 买卖股票的最佳时机
- LeetCode——121. 买卖股票的最佳时机
- LeetCode-121.买卖股票的最佳时机(相关话题:动态规划)
- 利用python 完成leetcode 122 买卖股票的最佳时机 II
- LeetCode 买卖股票的最佳时机(C++)
- LeetCode-122.买卖股票的最佳时机II(相关话题:贪心算法)
- leetcode-买卖股票的最佳时机 II
- leetcode-买卖股票的最佳时机(动态规划)
- leetcode122. 买卖股票的最佳时机 II
- [Leetcode] Best time to buy and sell stock 买卖股票的最佳时机
- LeetCode-123.买卖股票的最佳时机III(相关话题:动态规划)
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- C++Leetcode121:买卖股票的最佳时机
- Leetcode121: 买卖股票的最佳时机
- leetcode122. 买卖股票的最佳时机 II
- Leetcode122:买卖股票的最佳时机 II
- (LeetCode 309)最佳买卖股票时机含冷冻期 [dp + 逆向思维]
- [Leetcode]2018.3.22买卖股票的最佳时机 II