您的位置:首页 > 编程语言 > Python开发

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: