122.买卖股票的最佳时机 II

本文深入探讨了力扣122题的股票交易策略算法,包括暴力求解法和更高效的贪心算法/动态规划法。文章详细解释了如何通过算法最大化股票交易利润,以及在特定条件下如何选择买入和卖出时机。

力扣122. 买卖股票的最佳时机 II

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:
输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。

示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

解题思路

确定通过交易能够获得的最大利润(交易次数没有限制),需要找出那些共同使得利润最大化的买入及卖出价格。
计算每天价格的差值temp,筛选使得temp>=0,则永不亏损,遍历整个数组,求和temp使之最大

一 、暴力求解/搜索法

就这道题来说暴力解法(“回溯搜索”、“回溯法)是比贪心算法难的,我自己写不出来
官方是重新定义一个函数来递进计算与所有可能的交易组合相对应的利润,并找出它们中的最大利润。比较难理解,有大佬将官方的递进函数拆解开写成if—else形式

附上大佬的“模拟游标,寻找买点”

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        x_cursor = 0
        earn = 0
        while x_cursor < len(prices):
            x_val = prices[x_cursor]
            y_cursor = x_cursor + 1
            best_y_val = None
            best_y_cursor = None
            while y_cursor < len(prices):
                # if y_cursor == x_cursor:
                #     break
                y_val = prices[y_cursor]
                if not best_y_val:
                    # 没有发现好的卖点
                    if x_val < y_val:
                        # 发现卖点
                        best_y_val = y_val
                        best_y_cursor = y_cursor
                    else:
                        # 没有卖点,当日不买,换一天
                        break
                else:
                    # 有卖点,再找更好的卖点
                    if best_y_val < y_val:
                        best_y_val = y_val
                        best_y_cursor = y_cursor
                    else:
                        break
                y_cursor = y_cursor + 1
            if best_y_val:
                earn = earn + best_y_val - x_val
                x_cursor = best_y_cursor + 1
                best_y_val = None
            else:
                x_cursor = x_cursor + 1
        return earn

作者:li-yi-feng-3
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/python3bao-li-jie-fa-by-li-yi-feng-3/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

二、贪心算法/动态规划

参照最大子序和。
很多贪心算法和动态规划是一样的,只需要略微修改一下代码。
就我个人而言,从后往前的算法流程的逻辑更加通顺,等价于每天都买卖。
因为利润满足price=p(i)-p(j)=p(i)-p(i-1)+p(i-1)-p(i-2)+…+p(j+1)-p(j)
price>0表示盈利,price<=0表示不盈利,所有盈利累加就是最大盈利
及策略是所有上涨交易日都买卖(赚到所有利润)。
在此过程中每个数据只使用了一次或者没有使用,满足同一天只能进行一次操作的题意。

#python3 从后往前
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        maxprofit=0
        for i in range(len(prices)-1,0,-1):
            maxprofit+=prices[i]-prices[i-1] if prices[i]>prices[i-1] else 0
        return maxprofit
#python3 从前往后
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(1, len(prices)):
            tmp = prices[i] - prices[i - 1]
            if tmp > 0: profit += tmp
        return profit
以下是几种使用 Java 语言解决 LeetCode 121 题(买卖股票最佳时机)的方法: ### 方法一 ```java public class LeetCode { public int maxProfit(int[] prices) { int minPrice = Integer.MAX_VALUE; int maxProfit = 0; for (int i = 0; i < prices.length; i++) { if (prices[i] < minPrice) { minPrice = prices[i]; } else if (prices[i] - minPrice > maxProfit) { maxProfit = prices[i] - minPrice; } } return maxProfit; } } ``` 此方法中,`minPrice` 用于记录遍历过程中的最低股票价格,初始值设为 `Integer.MAX_VALUE`;`maxProfit` 用于记录最大利润,初始值为 0。通过遍历数组,不断更新 `minPrice` 和 `maxProfit`,最终返回最大利润 [^2]。 ### 方法二 ```java class Solution { public int maxProfit(int[] prices) { if(prices.length <= 1) return 0; int min = prices[0], max = 0; for(int i = 1; i < prices.length; i++) { max = Math.max(max, prices[i] - min); min = Math.min(min, prices[i]); } return max; } } ``` 该方法先判断数组长度是否小于等于 1,若是则直接返回 0。然后初始化 `min` 为数组第一个元素,`max` 为 0。在遍历数组时,使用 `Math.max` 函数更新最大利润 `max`,使用 `Math.min` 函数更新最低价格 `min`,最后返回最大利润 [^3]。 ### 方法三(暴力解法) ```java class Solution { public int maxProfit(int[] prices) { int res = 0; int temp = 0; for (int i = 0; i < prices.length; i++) { for (int j = i; j < prices.length; j++) { if (prices[j] > prices[i]) { temp = prices[j] - prices[i]; if (temp > res) { res = temp; } } } } return res; } } ``` 此为暴力解法,使用两层循环,外层循环 `i` 假设当前元素为最低价格,内层循环 `j` 假设当前元素为最高价格,计算利润并更新最大利润 `res`,最后返回最大利润 [^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值