python买卖股票_Python实现"买卖股票的最佳时机"的一种方法

给定一个数组,该数组中第i个元素是某个股票第i天的价钱

如果最多只能完成一次交易(买入股票,卖出股票),设计一个算法,可以获得最大的利润

注意:在你买入股票之前不能卖出股票

Example 1:

Input: [7,1,5,3,6,4]

Output: 5

Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]

Output: 0

Explanation: In this case, no transaction is done, i.e. max profit = 0.

1:申明三个变量,头指针pre、尾指针tail和最大利润maxProfit,头指针指向当前访问到的数组的最小值,尾指针指向当前访问到的最大值

访问数组prices,如果出现i-pre

继续访问数组,如果出现i-pre>tail-pre就替换tail为i(i元素值必定大于尾指针tail值),并且替换maxProfit的值为max(maxProfit,i-pre)

def maxProfit(self, prices):

"""

:type prices: List[int]

:rtype: int

"""

if len(prices)<=1:

return 0

pre = prices[0]

tail = prices[0]

maxProfit = 0

for i in range(1,len(prices)): #从第二个元素开始访问数组

if prices[i]-pre<0: #替换头指针和尾指针为当前访问到的数组的最小值

pre = prices[i]

tail = prices[i]

if prices[i]-pre>tail-pre: #替换尾指针为当前访问(从最小数值开始)的最大值

maxProfit = max(prices[i]-pre, maxProfit) #对比此时利润和之前保存的最大利润,返回现阶段可获得的最大利润

tail = prices[i]

return maxProfit

2:暴力法O(n^2),错误:超出时间限制

def maxProfit(self, prices):

"""

:type prices: List[int]

:rtype: int

"""

maxProfit = 0

for i in range(len(prices)):

for j in range(i+1,len(prices)):

if prices[j]-prices[i]>maxProfit:

maxProfit = prices[j]-prices[i]

return maxProfit

算法题来自:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值