[LeetCode刷题笔记]122 - 买卖股票的最佳时机 II(C++/Python3/Java/暴力/动态规划/贪心)

一、题目描述

  • 给定一个整数数组 prices ,它的第 i 个元素 prices[i] 表示某支股票第 i 天的价格。
  • 在每一天,你可以决定是否购买和/或出售股票。你在任何时候最多只能持有一股股票。你也可以先购买,然后在同一天出售。
  • 返回你能获得的最大利润 。

示例:

输入输出解释
prices = [7,1,5,3,6,4]7在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。总利润为 4 + 3 = 7 。
prices = [1,2,3,4,5]4在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。总利润为 4 。
prices = [7,6,4,3,1]0在这种情况下, 交易无法获得正利润,所以不参与交易可以获得最大利润,最大利润为 0 。

提示:

  • 1 < = p r i c e s . l e n g t h < = 3 ∗ 1 0 4 1 <= prices.length <= 3*10^4 1<=prices.length<=3104
  • 0 < = p r i c e s [ i ] < = 1 0 4 0 <= prices[i] <= 10^4 0<=prices[i]<=104

二、求解思路

方法一:暴力搜索(超出时间限制,不推荐)

首先分析出所有可能的情况,画成树形图,然后对其编程(回溯的思想求解)。(只给出 java 代码仅供参考)
在这里插入图片描述
Java代码

public class Solution {

    private int res;

    public int maxProfit(int[] prices) {
        int len = prices.length;
        if (len < 2) {
            return 0;
        }
        this.res = 0;
        dfs(prices, 0, len, 0, res);
        return this.res;
    }

    /**
     * @param prices 股价数组
     * @param index  当前是第几天,从 0 开始
     * @param status 0 表示不持有股票,1表示持有股票,
     * @param profit 当前收益
     */
    private void dfs(int[] prices, int index, int len, int status, int profit) {

        if (index == len) {
            this.res = Math.max(this.res, profit);
            return;
        }

        dfs(prices, index + 1, len, status, profit);

        if (status == 0) {
            // 可以尝试转向 1
            dfs(prices, index + 1, len, 1, profit - prices[index]);

        } else {
            // 此时 status == 1,可以尝试转向 0
            dfs(prices, index + 1, len, 0, profit + prices[index]);
        }
    }
}

方法二:二维动态规划

  • 定义状态 dp[i][0] 表示第 i 天交易完后手里没有股票的最大利润;
  • 定义状态 dp[i][1] 表示第 i 天交易完后手里持有股票的最大利润;
  • 状态转移方程:
    • 考虑dp[i][0]的转移,无非是上一天没有股票这一天也没买或者是上一天持有股票而这一天卖了,求这两种情况下的最大利润即可:
      • dp[i][0] = max{dp[i−1][0], dp[i−1][1] + prices[i]}
    • 考虑dp[i][1]的转移,无非是上一天持有股票这一天没卖或者是上一天没有股票而这一天买了,求这两种情况下的最大利润即可:
      • dp[i][1] = max{dp[i−1][1], dp[i−1][0] - prices[i]}
  • 明确初值:dp[0][0] = 0 and dp[0][1] = -prices[0]
  • 最终由于 dp[n-1][0] > dp[n-1][1] ,最大利润即为 dp[n-1][0] ,返回即可。

C++代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        int status_profit[n][2];
        status_profit[0][0] = 0;
        status_profit[0][1] = -prices[0];
        for(int i = 1; i < n; i++) {
            status_profit[i][0] = max(status_profit[i-1][0],status_profit[i-1][1]+prices[i]);
            status_profit[i][1] = max(status_profit[i-1][0]-prices[i],status_profit[i-1][1]);
        }
        return status_profit[n-1][0];
    }
};

Python3代码

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        dp = [[0]*2]*n
        dp[0][0] = 0
        dp[0][1] = -prices[0]
        for i in range(1,n):
            dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
            dp[i][1] = max(dp[i-1][0] - prices[i], dp[i-1][1])
        
        return dp[n-1][0]

Java代码

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int[][] dp = new int[n][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for(int i = 1; i < n; i++) {
            if(dp[i-1][1] + prices[i] > dp[i-1][0]) dp[i][0] = dp[i-1][1] + prices[i];
            else dp[i][0] = dp[i-1][0];
            if(dp[i-1][0] - prices[i] > dp[i-1][1]) dp[i][1] = dp[i-1][0] - prices[i];
            else dp[i][1] = dp[i-1][1];
        }

        return dp[n-1][0];
    }
}

复杂度分析

  • 时间复杂度: O ( n ) O(n) O(n),其中 n n n 为数组的长度。一共有 2 n 2n 2n 个状态,每次状态转移的时间复杂度为 O ( 1 ) O(1) O(1),因此时间复杂度为 O ( 2 n ) = O ( n ) O(2n)=O(n) O(2n)=O(n)
  • 空间复杂度: O ( n ) O(n) O(n),我们需要开辟 O ( n ) O(n) O(n) 空间存储动态规划中的所有状态。
  • 注意:该方法可以进行空间复杂度的改进,考虑到每一时刻的状态只与上一时刻有关,则只要保存上一时刻的状态即可。改进后的空间复杂度为 O ( 1 ) O(1) O(1)

方法三:贪心算法(推荐)

  • 由于交易次数不受限,因此我们可以把所有的相邻两日票价只差为正数的全部加起来即为最大利润。
  • 怎么理解呢?
    • 因为本题的意思就是要寻求x个不相交区间的最大的利润和,其中x无限制。而每一个区间的利润 prices[j] - prices[i] 等价于 (prices[j] - prices[j-1]) + (prices[j-1] - prices[j-2]) + ... + (prices[i+1] - prices[i]) ,由此可以把区间的利润分成多个相邻区间的利润和来计算。则如果需要求得最大利润时,只要满足每个相邻区间的利润为正数即可。

C++代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int profit = 0;
        for(int i = 1; i < prices.size(); i++) {
            if(prices[i] - prices[i-1] > 0) profit += prices[i] - prices[i-1];
        }
        
        return profit;
    }
};

Python3代码

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(1,len(prices)):
            if(prices[i] - prices[i-1] > 0):
                profit += prices[i] - prices[i-1]
        
        return profit

Java代码

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for(int i = 1; i < prices.length; i++) {
            if(prices[i] - prices[i-1] > 0) profit += prices[i] - prices[i-1];
        }

        return profit;
    }
}

复杂度分析

  • 时间复杂度: O ( n ) O(n) O(n),其中 n n n 为数组的长度。
  • 空间复杂度: O ( 1 ) O(1) O(1)

三、参考文章

[1] https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/solution/mai-mai-gu-piao-de-zui-jia-shi-ji-ii-by-leetcode-s/
[2] https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/solution/tan-xin-suan-fa-by-liweiwei1419-2/ (推荐阅读)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PanyCG_pc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值