[leetcode]Best Time to Buy and Sell Stock III @ Python

本文详细介绍了如何使用动态规划解决在股票市场中进行最多两次交易以获取最大利润的问题。通过创建两个数组分别记录在任意时刻之前和之后进行一次交易的最大利润,最终求解两个数组元素之和的最大值,实现高效的投资决策。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题地址:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

题意:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

解题思路: 交易市场的“低买高卖" 法则(buy low and sell high' )

只允许做两次交易,这道题就比前两道要难多了。解法很巧妙,有点动态规划的意思:

开辟两个数组p1和p2,p1[i]表示在price[i]之前进行一次交易所获得的最大利润,

p2[i]表示在price[i]之后进行一次交易所获得的最大利润。

则p1[i]+p2[i]的最大值就是所要求的最大值,

而p1[i]和p2[i]的计算就需要动态规划了,看代码不难理解。

 

复制代码
class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        n = len(prices)
        if n <= 1: return 0
        p1 = [0] * n
        p2 = [0] * n
        
        minV = prices[0]
        for i in range(1,n):
            minV = min(minV, prices[i])       # Find low and buy low
            p1[i] = max(p1[i - 1], prices[i] - minV)
        
        maxV = prices[-1]
        for i in range(n-2, -1, -1):
            maxV = max(maxV, prices[i])     # Find high and sell high
            p2[i] = max(p2[i + 1], maxV - prices[i])
        
        res = 0
        for i in range(n):
            res = max(res, p1[i] + p2[i])
        return res
复制代码

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值