LeetCode:买卖股票的最佳时机(Python版)
2019-03-20 15:57
471 查看
LeetCode刷题日记
买卖股票的最佳时机
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 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。
Python代码
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ temp = [] # 存放差值 if not prices or len(prices) == 1: # 特殊情况,输入为空或者只有一个元素的情况 return 0 for i in range(len(prices) - 1): # 当前值和后面的最大值做差 temp.append(max(prices[i + 1:]) - prices[i]) if max(temp) >= 0: # 如果利润大于等于0,那么输出 return max(temp) else: # 利润小于0的情况 return 0
这道题不是很难,但是也体现了薄弱的数据结构,意识到这一点,现在开始恶补数据结构,一开始问题想的简单了,导致了题目提交超时,下面贴上超时代码,给自己提个醒,好好学数据结构。。
class Solution(object): # 超时 def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ res = [] if not prices: return 0 for i in range(len(prices)-1): for j in range(i+1, len(prices)): tmp = prices[j] - prices[i] if tmp >= 0: res.append(tmp) continue if not res: return 0 return max(res)
相关文章推荐
- LeetCode 122 买卖股票的最佳时机2 Python
- 利用python 完成 leetcode123 买卖股票的最佳时机 III
- LeetCode 121 买卖股票的最佳时机 Python
- 利用python 完成leetcode 122 买卖股票的最佳时机 II
- LeetCode 买卖股票的最佳时间系列习题 python(上)
- [Leetcode]2018.3.22买卖股票的最佳时机 II
- [Leetcode] Best time to buy and sell stock iii 买卖股票的最佳时机
- leetcode 309. 最佳买卖股票时机含冷冻期
- LeetCode-123.买卖股票的最佳时机III(相关话题:动态规划)
- 算法学习——leetcode122. 买卖股票的最佳时机 II
- (LeetCode 309)最佳买卖股票时机含冷冻期 [dp + 逆向思维]
- LeetCode 122. 买卖股票的最佳时机 II
- Leetcode 121. 买卖股票的最佳时机
- LeetCode(初级算法)数组篇--买卖股票的最佳时机 II c++
- Java&LeetCode 初入门——122. 买卖股票的最佳时机 II
- LeetCode 121. 买卖股票的最佳时机
- LeetCode 123. 买卖股票的最佳时机 III
- LeetCode 122. 买卖股票的最佳时机 II
- [Java语言] [Leetcode] Best Time to Buy and Sell Stock 买卖股票的最佳时机
- C++Leetcode121:买卖股票的最佳时机