LeetCodes——Best Time to Buy and Sell Stock【系列问题】

Best Time to Buy and Sell Stock系列问题在面试过程中经常遇到,这里将下面几种问题做一个总结。
1.121 Best Time to Buy and Sell Stock
2.122 Best Time to Buy and Sell Stock II
3.123 Best Time to Buy and Sell Stock III
4.188 Best Time to Buy and Sell Stock IV
5.309 Best Time to Buy and Sell Stock with Cooldown
6.714 Best Time to Buy and Sell Stock with Transaction Fee

121 Best Time to Buy and Sell Stock 题目要求

Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
只允许一次股票交易

解题思路

只允许一次交易,思路就是去找到在前一段区间内最小的数,和后一段区间内最大的数,二者之差即为最大收益。
怎么去寻找最小值?用迭代的方式,通过遍历数组,我们可以设置一个min变量来保存当前时刻的最小值,最大收益值则是不断用当前值减去最小值,不断的更新min值以及最大收益值。

代码

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

代码结果

200 / 200 test cases passed.
Status: Accepted
Runtime: 8 ms

122 Best Time to Buy and Sell Stock II 题目要求

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
可以进行无限多次交易

解题思路

因为可以进行无限次,那么只要我们发现前后两数呈递增关系,则可以进行交易。

代码

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

代码结果

198 / 198 test cases passed.
Status: Accepted
Runtime: 12 ms

123 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.
至多两次交易

解题思路

我们可以在数组中间画条线,在左边进行第一次交易,在右边进行第二次交易,来计算两次交易的最大收益和。这样,就将问题简化为只进行一次交易的问题了。

代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
//遍历,计算出第x天之前一次交易可以得到的最大收益,存储在formmer[n]中
//遍历,计算出第x天之后一次交易可以得到的最大收益,存储在latter[n]中
//遍历,计算formmer[i] + latter[i] 得到最大收益max
        if (prices.size()<2){
            return 0;
        }
        int n = prices.size();
        vector<int> former(n,0);
        vector<int> latter(n,0);
        int minPrices = INT_MAX;
        int maxPro = 0;
        for (int i=0;i<n;i++){
            minPrices = min(minPrices,prices[i]);
            maxPro = max(maxPro,prices[i]-minPrices);
            former[i] = maxPro;
        }
        int maxPrices = INT_MIN;
        int maxPro1 = 0;
        for (int i=n-1;i>=0;i--){
            maxPrices = max(maxPrices,prices[i]);
            maxPro1 = max(maxPro1,maxPrices-prices[i]);
            latter[i] = maxPro1;
        }
        int res = 0;
        for (int i=0;i<n;i++){
            res = max(res,former[i]+latter[i]);
        }
        return res;
    }
};

代码结果

198 / 198 test cases passed.
Status: Accepted
Runtime: 8 ms

188 Best Time to Buy and Sell Stock IV 题目要求

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 k transactions.
最多进行K次交易

解题思路

这道题比较难,用DP来求解,网上用local和global的思路比较复杂,看到一个比较容易理解的思路在这里给大家推荐。用两个数组buy和sell来分别表示第j次买入交易的最大收益值和第j次卖出交易的最大收益值。这样,DP状态转移方程为:

buy[j] = max(buy[j],sell[j-1]-prices[i]); //在第i点处进行第j次买入交易。
sell[j] = max(sell[j],buy[j]+prices[i]);//在第i点处进行第j次卖出交易。

此外,用quickSolve函数来解决若k太大引起的超时问题。简化到允许多次交易问题上。

代码

class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        int len = prices.size();
        if(len == 0){
            return 0;
        }else if (len/2 < k){
            return quickSolve(prices);
        }
        vector<int> buy(k+1,INT_MIN);//第k次交易买入的最大收益;
        vector<int> sell(k+1,0);//第k次交易卖出的最大收益;
        for (int i=0;i<len;i++){
            for (int j=1;j<=k;j++){
                buy[j] = max(buy[j],sell[j-1]-prices[i]);
                sell[j] = max(sell[j],buy[j]+prices[i]);
            }
        }
        return sell[k];
    }
     int quickSolve(vector<int>& prices) {
        int len = prices.size(), profit = 0;
        for (int i = 1; i < len; i++)
            // as long as there is a price gap, we gain a profit.
            if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
        return profit;
    }
};

代码结果

211 / 211 test cases passed.
Status: Accepted
Runtime: 7 ms

309. Best Time to Buy and Sell Stock with Cooldown题目要求

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
1.You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
2.After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
sell和buy之间至少需要一天的休息时间

解题思路

由于sell和buy之间至少需要一天的rest,因此这道题中有三种状态,每种状态之间的转换如下:
其中buy[i]表示第i天买入的最大收益值,sell[i]表示第i天卖出的最大收益值,rest[i]表示第i天休息时的最大收益值。

buy[i] = max(buy[i-1],rest[i-1]-prices[i]);
sell[i] = max(sell[i-1],buy[i-1]+prices[i]);
rest[i] = max(max(sell[i-1],buy[i-1]),rest[i-1]);

代码

class Solution {//状态切换
public:
    int maxProfit(vector<int>& prices) {
        if (prices.empty())
            return 0;
        int buy = INT_MIN;
        int sell = 0;
        int rest = 0;
        int prev_buy = buy;
        int prev_sell = sell;
        int prev_rest = rest;
        for (int i=0;i<prices.size();i++){
            buy = max(prev_buy,prev_rest-prices[i]);
            sell = max(prev_sell,prev_buy+prices[i]);
            rest = max(max(prev_sell,prev_buy),prev_rest);
            prev_buy = buy;
            prev_sell = sell;
            prev_rest = rest;
        }
        return sell;
    }
};

代码结果

211 / 211 test cases passed.
Status: Accepted
Runtime: 10 ms

714 Best Time to Buy and Sell Stock with Transaction Fee题目要求

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
Return the maximum profit you can make.
每次交易有手续费fee

解题思路

这道题依然可以用状态转换的思想来做,s0[i]表示在第i天手上没有持股的最大收益值,s1[i]表示第i天手上持有一股的最大收益值。那么二者的转换为:

s0[i] = max(s0[i-1], s1[i-1]+prices[i]);
s1[i] = max(s1[i-1], s0[i-1]-prices[i]-fee);

代码

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        //s0 = profit having no stock
        //s1 = profit having 1 stock
        int s0 = 0, s1 = INT_MIN; 
        for(int p:prices) {
            int tmp = s0;
            s0 = max(s0, s1+p);
            s1 = max(s1, tmp-p-fee);
        }
        return s0;
    }
};

代码结果

44 / 44 test cases passed.
Status: Accepted
Runtime: 139 ms

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值