Leetcode中股票问题合集

  1. Best Time to Buy and Sell Stock II
    思路:这道题用到了贪心算法。从第二天开始,只要比前一天大,那说明就挣钱,那么就前一天买今天卖,挣差价。
int maxProfit(vector& prices) {
        int res = 0;
        int n = prices.size();
        for (int i = 0; i < n - 1; i++) {
            if (prices[i] < prices[i+1])
                res += prices[i+1] - prices[i];
        }
        return res;
    }
  1. Best Time to Buy and Sell Stock III
    思路:本身并不是特别懂,可看博客。
    用两个递推公式,分别更新两个变量local和global。定义local[i][j]为在第i天之前最多交易j次,并且最后一天必须交易,获得的最大利润,global[i][j]定义为在第i天前最多交易j次,获得的最大利润。
    local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i - 1][j] + diff)
    global[i][j] = max(local[i][j], global[i - 1][j])
    diff = prices[i+1]-prices[i]
int maxProfit(vector& prices) {
        if (prices.empty())
            return 0;
        int n = prices.size();
        int g[n][3] = {0},l[n][3] = {0};
        for (int i = 1; i < n; i++) {
            int diff = prices[i] - prices[i-1];
            for (int j = 1; j <= 2; j++) {
                l[i][j] = max(g[i-1][j-1] + max(diff,0),l[i-1][j]+diff);
                g[i][j] = max(g[i-1][j],l[i][j]);
            }
        }
        return g[n-1][2];
    }

思路2:既然最多买两次,那么就分成两段。第一段求prices[0,i]上最大收益,第二段求prices[i,n-1]上最大收益,然后两个加起来就可以。求最大收益直接用Best Time to Buy and Sell Stock I中的方法,但是如果写在同一个循环中比如下方代码,时间复杂度就是O(n^2)。所以不能用这种方法,同样的思路,但是要减小时间复杂度,那么我们先正向扫描,保存没天交易的最大收益到数组,然后反向扫描,保存每天收益的最小值到数组,然后再遍历,以第i天为中心,左右两边的收益相减,就是最大收益。

for (int i = 0; i < n; i++) {
    p1 = maxProfit(prices[0,i]);    //O(n*n)
    p2 = maxProfit(prices[i,n-1]);  // O(n*n)
    max_p = max(p1+p2,max_p);
}
int maxProfit(vector& prices) {
        if (prices.empty()) return 0;
        int n = prices.size();
        vector first(n,0);
        vector second(n,0);
        int min_buy = prices[0];
        int res = 0;
        for (int i = 1; i < n; i++) {
            min_buy = min(min_buy,prices[i]);
            first[i] = max(first[i-1],prices[i]-min_buy);
        }
        int max_buy = prices[n-1];
        for (int i = n-2; i >= 0 ; i--) {
            max_buy = max(max_buy,prices[i]);
            second[i] = min(second[i+1],prices[i] - max_buy);
        }
        for (int i = 0; i < n; i++) {
            res = max(res,first[i]-second[i]);
        }
        return res;
    }

714.Best Time to Buy and Sell Stock with Transaction Fee
思路:这里多了一个买卖股票需要扣除费用。对于第i天来说,手中要么没有股票,要么手持一个股票。用sold表示第i天没有股票的收益,hold表示第i天手持股票的收益。
没有股票的情况:要么是前一天就没有股票,要么是今天卖掉了,所以这种情况下,最大值就是比较这两者。sold[i] = max(sold[i-1],hold[i-1]+price[i]-fee)
手持股票的情况:要么是前一天就持有股票,要么今天买的股票,取其中最大值。
hold[i] = max(hold[i-1],sold[i-1] - price[i])

int maxProfit(vector& prices, int fee) {
        int sold = 0,hold = -prices[0];
        for (int i = 1; i < prices.size(); i++) {
            sold = max(sold,hold + prices[i] - fee);
            hold = max(hold,sold - prices[i]);
        }
        return sold;
    }

你可能感兴趣的:(C++,算法,LeetCode)