LintCode 买卖股票的最佳时期I II III 之Python 代码

假设你有一个数组,它的第i个元素是一支给定的股票在第i天的价格。设计一个算法来找到最大的利润。
I:如果你最多只允许完成一次交易。
II:你可以完成尽可能多的交易(多次买卖股票)。
III:你最多可以完成两笔交易。

买卖股票的最佳时期I

(I)简单粗暴的思路:双指针遍历所有情况,选择最大利润。时间复杂度 O(n2)
代码如下:

class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """
    def maxProfit(self, prices):
        # write your code here
        result = 0
        for i in range(len(prices)-1):
            for j in range(i + 1, len(prices)):
                result  = max(result, prices[j] - prices[i])
        return result
     #The shortest running time is about 1500ms.

(II)动态规划:选取最小的价格购买,保留最大的利润。只需一次遍历。时间复杂度 O(n)
代码如下:

class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """
    def maxProfit(self, prices):
        # write your code here
        # if len(prices) < 2:return 0
        if prices is None or len(prices) == 0:
            return 0
        Begin_value = prices[0]
        result = 0                #初始化结果为0
        for p in prices:
            result = max(result, p-Begin_value) 
            Begin_value = min(Begin_value, p)   
        return result

买卖股票的最佳时期II

有 I 的基础,这题便不难。只买涨的,不买跌的。
代码如下:

class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """
    def maxProfit(self, prices):
        # write your code here
        if prices is None or len(prices) < 2:
            return 0
        result = 0
        Begin_value= prices[0]
        for p in prices:
            if p > Begin_value:
                result += p-Begin_value  #涨股利润累加
                Begin_value = p          #重新买股
            else:
                Begin_value = min(Begin_value, p)
        return result

买卖股票的最佳时期III

解法一:

同 I 题最初的思路,简单粗暴:做一个遍历prices的指针index,将prices分成2部分,再分别算出2个部分的最大利润并返回其和的最大值,即为题设结果。时间复杂度 O(n2)
代码如下:

def maxProfit(self, prices):
        # write your code here
        if prices is None or len(prices) < 2:
            return 0
        result = 0
        def Solve(part):
            if part is None or len(part) == 0:
                return 0
            Min = part[0]
            res = 0
            for p in part:
                res = max(res, p-Min)
                Min = min(Min, p)
            return res

        for i in range(len(prices)-1):
            one = prices[:i]
            two = prices[i:]
            result = max(result, (Solve(one) + Solve(two)))
        return result 

解法二:

考虑到最多只能交易两次,我们先考虑交易一次,得到当次最大利润,再讨论第二次交易的情况。对于prices数组list,不妨设该次开始交易的指针为begin,卖出当前股票时指针为stop,那么整个list就被begin、stop指针分为3个part,其中我们在第一次交易时已求得part_2最大利润值。对于第二次交易,有三种情况,即可能处于part_1或part_2或part_3中。

(i)如果是part_1,则返回part_1及part_2最大利润的和;
(ii)如果是part_2,类似’N’型的折线,结果应当是第一次交易的最大利润加上两次极值转折跌价的差值
而两次极值转折跌价的差值实际是part_2倒序的最大利润值,也就是代码中Solve函数参数 t = -1 的情况;
(iii)如果是part_3,则返回part_2及part_3最大利润的和。
最后在选取上述三种情况的最大值。

相比 I 题,我们只需在求解最大利润的同时找到其开始买入(begin)以及卖出股票(stop)的list指针,在分别算出3个part的最大利润,最后返回题设的最大利润。

class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """
    def maxProfit(self, prices):
        # write your code here
        if prices is None or len(prices) < 2:
            return 0
        def Solve(part, t):
            if t == -1:
                part = part[::-1]
            if part is None or len(part) < 2:
                return 0
            Begin_value = part[0]
            result = 0
            for p in part:
                result = max(result, p-Begin_value)
                Begin_value = min(Begin_value, p)
            return result

        begin, index, stop = 0, 0, 1    #开始买入指针,临时指针,结束卖出指针
        Sum, Max = 0, 0
        for i in range(len(prices)-1):
            Sum += prices[i+1]-prices[i]
            if Sum > Max:
                Max = Sum
                stop = i + 1
                begin = index
            Sum = max(0, Sum)
            if Sum == 0:
                index = i + 1
        part_1 = Max + Solve(prices[:begin], 1)
        part_2 = Max + Solve(prices[begin:stop+1], -1)if Max > 0 else 0
        part_3 = Max + Solve(prices[stop+1:], 1)
        #part_2中的判断语句是因为可能出现part_2最大利润Max为0,即递减数组,而第二次交易又在此part,第二次的最大利润>0,矛盾。
        return max(part_1, part_2, part_3)

当然还另有终极版本的,也就是找出至多交易k次的最大利润。
参考[Code Ganker的博客]动态规划结合递推求解。(http://blog.csdn.net/linhuanmars/article/details/23236995)
目前想到一个划分合并的方法,不过细节处理有些复杂,还得细细考虑优化算法来处理这些细节。占个坑,以后想到了再补充。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值