【算法面试通关40讲】48 - 面试题:股票买卖系列

121(只能买卖一次),122(可以买卖无数次),123(只能买卖两次),309(加入了cool down),188(可以买卖k次),714(交易含有手续费怎么办)

Leetcode-121. 买卖股票的最佳时机

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。

示例 2:

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

解法:遍历一遍,同时记录前面的最小值

  • Java
class Solution {
    public int maxProfit(int[] prices) {
        // 一次遍历,记录最小值
        if (prices==null || prices.length==0) return 0;
        int min = prices[0], res = 0;
        for (int i=1;i<prices.length;i++) {
            if (prices[i] < min) {
                min = prices[i];
            } else if(prices[i]-min>res) {
                res = prices[i]-min;
            } else {}
        }
        return res;
    }
}
  • Python
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices: return 0
        min, res = prices[0], 0
        for i in range(1, len(prices)):
            if prices[i]<min:
                min = prices[i]
            elif prices[i]-min>res:
                res = prices[i] - min
            else: pass
        return res

Leetcode-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:

输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
     注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
     因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。

示例 3:

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

解法:贪婪算法,只要明天价格涨了,我们就买入。

  • Java
class Solution {
    public int maxProfit(int[] prices) {
        if (prices==null || prices.length==0) return 0;
        int res = 0;
        for (int i=0;i<prices.length-1;i++) {
            if (prices[i]<prices[i+1]) {
                res += prices[i+1]-prices[i];
            }
            else{}
        }
        return res;
    }
}
  • Python
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices: return 0
        res = 0
        for i in range(0, len(prices)-1):
            if prices[i+1]>prices[i]:
                res += prices[i+1]-prices[i]
            else:
                pass
        return res

Leetcode-123. 买卖股票的最佳时机 III

给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。

注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:

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

示例 2:

输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。   
     注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。   
     因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。

示例 3:

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

Leetcode-188. 买卖股票的最佳时机 IV

给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。

注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:

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

示例 2:

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

解法:使用DP,首先要定义状态dp[i],含义设定为第i天能够获得的最大利润,然后推导递推方程dp[i] = dp[i-1] - prices[i](第i天买入)或者dp[i] = dp[i-1] + prices[i](第i天卖出),但是这样定义,没有办法知道第i天到底是哪种方程,因此需要改进递推公式,增加维度,i表示天数,从0到n-1,k表示买卖的次数,从0到k,j表示拥有的股票数,0或1,那么dp[i][k][j]的状态含义就是第i天进行了k次交易手头(只有卖出才算交易+1)拥有j个股票时,能获得的最大利润,递推公式如下图所示,(i, j, k)的先后顺序不重要

在这里插入图片描述

最终的收益就是MP[n-1][{0~k}][0](也就是说最后一天,完成了0-k笔交易,并且最后手头没有股票的情况)中的最大值

  • Java
    k=2
class Solution {
    public int maxProfit(int[] prices) {
        if (prices==null || prices.length==0) return 0;
        long[][][] mp = new long[prices.length][3][2]; // 3 for 0,1,2 trades been made ,2 for 0,1 stocks we have in hand
        mp[0][0][0] = 0; mp[0][0][1] = -prices[0];
        mp[0][1][0] = Integer.MIN_VALUE; mp[0][1][1] = Integer.MIN_VALUE;
        mp[0][2][0] = Integer.MIN_VALUE; mp[0][2][1] = Integer.MIN_VALUE;
        for (int i=1;i<prices.length;i++) {
            mp[i][0][0] = mp[i-1][0][0];
            mp[i][0][1] = Math.max(mp[i-1][0][1], mp[i-1][0][0]-prices[i]);
            
            mp[i][1][0] = Math.max(mp[i-1][1][0], mp[i-1][0][1]+prices[i]);
            mp[i][1][1] = Math.max(mp[i-1][1][1], mp[i-1][1][0]-prices[i]);
            
            mp[i][2][0] = Math.max(mp[i-1][2][0], mp[i-1][1][1]+prices[i]);
        }
        return (int)Math.max(mp[prices.length-1][0][0]<mp[prices.length-1][1][0]?mp[prices.length-1][1][0]:mp[prices.length-1][0][0], mp[prices.length-1][2][0]);
    }
}
  • Python
    k=2
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices: return 0
        length = len(prices)
        mp = [[[0 for _ in range(2)] for _ in range(3)] for _ in range(length)]
        minint = -2**31
        mp[0][0][0], mp[0][0][1] = 0, -prices[0]
        mp[0][1][0], mp[0][1][1] = minint, minint
        mp[0][2][0], mp[0][2][1] = minint, minint
        for i in range(1, len(prices)):
            mp[i][0][0] = mp[i-1][0][0]
            mp[i][0][1] = max(mp[i-1][0][1], mp[i-1][0][0]-prices[i])
            
            mp[i][1][0] = max(mp[i-1][1][0], mp[i-1][0][1]+prices[i])
            mp[i][1][1] = max(mp[i-1][1][1], mp[i-1][1][0]-prices[i])
            
            mp[i][2][0] = max(mp[i-1][2][0], mp[i-1][1][1]+prices[i])
        return max(mp[length-1][0][0], mp[length-1][1][0], mp[length-1][2][0])
  • Java
    k笔交易
class Solution {
    public int maxProfit(int K, int[] prices) {
        if (prices==null || prices.length==0 || K<=0) return 0;
        if (K>=prices.length/2) { // equal to that you can make maximum number of transactions.
            int res = 0;
            for (int i=0;i<prices.length-1;i++) {
                if (prices[i+1]>prices[i]) {
                    res += prices[i+1]-prices[i];
                }
            }
            return res;
        }
        
        int[][][] mp = new int[prices.length][K+1][2]; // mp for max_profit
        List<Integer> res = new ArrayList<>();
        mp[0][0][0] = 0; mp[0][0][1] = -prices[0];
        for (int k=1;k<=K;k++) {
            mp[0][k][0] = -(int)Math.pow(2,10); // set a minus value meaning impossible option
            mp[0][k][1] = -(int)Math.pow(2,10);
        }
        
        for (int i=1;i<prices.length;i++) {
            mp[i][0][0] = mp[i-1][0][0];
            mp[i][0][1] = Math.max(mp[i-1][0][1], mp[i-1][0][0]-prices[i]);
            for (int k=1;k<K;k++) {
                mp[i][k][0] = Math.max(mp[i-1][k][0], mp[i-1][k-1][1]+prices[i]);
                mp[i][k][1] = Math.max(mp[i-1][k][1], mp[i-1][k][0]-prices[i]);
            }
            mp[i][K][0] = Math.max(mp[i-1][K][0], mp[i-1][K-1][1]+prices[i]);
        }
        
        for (int k=0;k<=K;k++) { // max value are in mp[len(prices)-1][0~k][0], add to a list
            res.add(mp[prices.length-1][k][0]);
        }
        return Collections.max(res);
    }
}

这里再给出如果用递推做121,也就是1次交易的代码,以供参考

class Solution {
    public int maxProfit(int[] prices) {
        // 一次遍历,记录最小值
        if (prices==null || prices.length==0) return 0;
        int[][][] mp = new int[prices.length][2][2];
        mp[0][0][0] = 0; mp[0][0][1] = -prices[0];
        mp[0][1][0] = -(int)Math.pow(2,10); mp[0][1][1] = -(int)Math.pow(2,10);
        for (int i=1;i<prices.length;i++) {
            mp[i][0][0] = mp[i-1][0][0];
            mp[i][0][1] = Math.max(mp[i-1][0][1], mp[i-1][0][0]-prices[i]);
            mp[i][1][0] = Math.max(mp[i-1][1][0], mp[i-1][0][1]+prices[i]);
            mp[i][1][1] = Math.max(mp[i-1][1][1], mp[i-1][1][0]-prices[i]);
        }
        return Math.max(mp[prices.length-1][0][0],mp[prices.length-1][1][0]);
    }
}

Leetcode-309. 最佳买卖股票时机含冷冻期

给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。​

设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):

你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
示例:

输入: [1,2,3,0,2]
输出: 3 
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]

解法:与上题类似,定义dp状态,推导dp状态转移方程

  • Java
class Solution {
    public int maxProfit(int[] prices) {
        if (prices==null || prices.length==0) return 0;
        int[][][] mp = new int[prices.length][2][2]; // 天数,持股数,是否是冷冻期
        mp[0][0][0] = 0; mp[0][1][0] = -prices[0];
        mp[0][0][1] = -(int)Math.pow(2,10); mp[0][1][1] = -(int)Math.pow(2,10);
        for (int i=1;i<prices.length;i++) {
            mp[i][0][0] = Math.max(mp[i-1][0][0], mp[i-1][0][1]); // 前一天就是0股非冷冻,或者前一天0股是冷冻期
            mp[i][1][0] = Math.max(mp[i-1][1][0], mp[i-1][0][0]-prices[i]); // 前一天1股非冷冻期,前一天0股非冷,买入1股
            mp[i][0][1] = mp[i-1][1][0]+prices[i]; // 只能是前一天卖出了股票
            // mp[i][1][1] = mp[i-1][0][0]-prices[i];  // 不可能存在有1个股票的同时还是冷冻期
        }
        return Math.max(mp[prices.length-1][0][1], mp[prices.length-1][0][0]);
    }
}
  • Python
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices: return 0
        mp = [[[0 for _ in range(2)] for _ in range(2)] for _ in range(len(prices))]
        mp[0][0][0], mp[0][1][0], mp[0][0][1], mp[0][1][1] = 0, -prices[0], -pow(2,10), -pow(2,10)
        for i in range(1,len(prices)):
            mp[i][0][0] = max(mp[i-1][0][0], mp[i-1][0][1]) # 前一天就是0股非冷冻,或者前一天0股是冷冻期
            mp[i][1][0] = max(mp[i-1][1][0], mp[i-1][0][0]-prices[i]) # 前一天1股非冷冻期,前一天0股非冷,买入1股
            mp[i][0][1] = mp[i-1][1][0]+prices[i] # 只能是前一天卖出了股票
            # mp[i][1][1] = mp[i-1][0][0]-prices[i]  # 不可能存在有1个股票的同时还是冷冻期
        return max(mp[len(prices)-1][0][0], mp[len(prices)-1][0][1])

Leetcode-714. 买卖股票的最佳时机含手续费

给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。

你可以无限次地完成交易,但是你每次交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

返回获得利润的最大值。

示例 1:

输入: prices = [1, 3, 2, 8, 4, 9], fee = 2
输出: 8
解释: 能够达到的最大利润:  
在此处买入 prices[0] = 1
在此处卖出 prices[3] = 8
在此处买入 prices[4] = 4
在此处卖出 prices[5] = 9
总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

注意:

  • 0 < prices.length <= 50000.
  • 0 < prices[i] < 50000.
  • 0 <= fee < 50000.

解法:同上

  • Java
class Solution {
    public int maxProfit(int[] prices, int fee) {
        if (prices==null || prices.length<=1) return 0;
        int[][] mp = new int[prices.length][2]; // 天数,持股数
        mp[0][0] = 0; mp[0][1] = -prices[0];
        for (int i=1;i<prices.length;i++) {
            mp[i][0] = Math.max(mp[i-1][0],mp[i-1][1]+prices[i]-fee);
            mp[i][1] = Math.max(mp[i-1][1],mp[i-1][0]-prices[i]);
        }
        return mp[prices.length-1][0];
    }
}
  • Python
class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        if not prices or len(prices)<=1: return 0
        mp = [[0 for _ in range(2)] for _ in range(len(prices))]
        mp[0][0], mp[0][1], mp[1][0], mp[1][1] = 0, -prices[0], -pow(2,10), -pow(2,10)
        for i in range(1,len(prices)):
            mp[i][0] = max(mp[i-1][0], mp[i-1][1]+prices[i]-fee)
            mp[i][1] = max(mp[i-1][1], mp[i-1][0]-prices[i])
        return mp[len(prices)-1][0]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值