算法——股票问题

股票问题

一、买卖股票的最好时机(一次交易)

假设你有一个数组,其中第\ i i 个元素是股票在第\ i i 天的价格。
你有一次买入和卖出的机会。(只有买入了股票以后才能卖出)。请你设计一个算法来计算可以获得的最大收益。

输入:[1,4,2]       返回值:3

输入:[2,4,1]       返回值:2

class Solution:
    def maxProfit(self , prices ):
        # write code here
        if not prices:
            return 0
        m, n = 0, len(prices)
        buy = prices[0]
        sell = 0
        for i in range(1, n):
            #先买入
            buy = min(prices[i], buy) #记录买入的最小值
            #再卖出
            sell = max(sell, prices[i]-buy)
        return sell

 

二、买卖股票的最好时机(无限次交易)

定你知道某只股票每一天价格的变动。

你最多可以同时持有一只股票。但你可以无限次的交易(买进和卖出均无手续费)。

请设计一个函数,计算你所能获得的最大收益。

示例1

输入:[5,4,3,2,1]      返回值:0

说明:由于每天股票都在跌,因此不进行任何交易最优。最大收益为0。

示例2

输入:[1,2,3,4,5]     返回值:4

说明:第一天买进,最后一天卖出最优。中间的当天买进当天卖出不影响最终结果。最大收益为4

 

class Solution:
    def maxProfit(self , prices ):
        # write code here
        if not prices:
            return 0
        m, n = 0, len(prices)
        sell = 0 #不买不卖——最少收益为0,大于亏本情况
        buy = prices[0]
        for i in range(1, n):
            #不持有股票——先卖出的收益
            sell = max(sell, prices[i]- buy) #卖出- 比较行情价格-成本买入最低价
            #持有股票——  比较最小成本和 卖出再买入的成本(多次操作)
            buy = min(buy, prices[i] - sell) #买入- 比较买入取最小价,和当天做T的总成本。
                                             
        return sell

 

 

三、买卖股票的最好时机(限2次交易)

假定你知道某只股票每一天价格的变动。

你最多可以同时持有一只股票。但你最多只能进行两次交易(一次买进和一次卖出记为一次交易。买进和卖出均无手续费)。

请设计一个函数,计算你所能获得的最大收益。

示例1

输入:[8,9,3,5,1,3]     返回值:4

说明:第三天买进,第四天卖出,第五天买进,第六天卖出。总收益为4。

class Solution:
    def maxProfit(self , prices ):
        # write code here
        if not prices:
            return 0
        n = len(prices)
        buy1, buy2 = prices[0], prices[0]
        sell1, sell2 = 0, 0
        for i in range(n):
            buy1 = min(buy1, prices[i])
            sell1 = max(sell1, prices[i]-buy1)
            buy2 = min(buy2, prices[i]-sell1)
            sell2 = max(sell2, prices[i]-buy2)        
        return sell2

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值