A clean DP solution which generalizes to k transactions

有一个解决股票买卖问题(Best Time to Buy and Sell Stock)的模板,可以推广到买卖n次。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // f[k, ii] represents the max profit up until prices[ii] (Note: NOT ending with prices[ii]) using at most k transactions. 
        // f[k, ii] = max(f[k, ii-1], prices[ii] - prices[jj] + f[k-1, jj]) { jj in range of [0, ii-1] }
        //          = max(f[k, ii-1], prices[ii] + max(f[k-1, jj] - prices[jj]))
        // f[0, ii] = 0; 0 times transation makes 0 profit
        // f[k, 0] = 0; if there is only one price data point you can't make any money no matter how many times you can trade
        if (prices.size() <= 1) return 0;
        else {
            int K = 2; // number of max transation allowed
            int maxProf = 0;
            vector<vector<int>> f(K+1, vector<int>(prices.size(), 0));
            for (int kk = 1; kk <= K; kk++) {
                int tmpMax = f[kk-1][0] - prices[0];
                for (int ii = 1; ii < prices.size(); ii++) {
                    f[kk][ii] = max(f[kk][ii-1], prices[ii] + tmpMax);
                    tmpMax = max(tmpMax, f[kk-1][ii] - prices[ii]);
                    maxProf = max(f[kk][ii], maxProf);
                }
            }
            return maxProf;
        }
    }
};
另外,当k大于len/2时就可以用O(n)解决了,空间上的优化可以用翻滚数组,优化代码如下:

public class Solution {
    public int maxProfit(int k, int[] prices) {
        if (prices.length < 2) {
            return 0;
        } else {
            if (k > prices.length / 2) {
                return quickSolution(prices);
            }
            int[][] dp = new int[2][prices.length];
            //int max = 0;
            for (int kk = 1; kk <= k; kk ++) {
                int tempPro = dp[(kk - 1) % 2][0] - prices[0];
                for (int i = 1; i < prices.length; i ++) {
                    dp[kk % 2][i] = Math.max(dp[kk % 2][i - 1], prices[i] + tempPro);
                    tempPro = Math.max(tempPro, dp[(kk - 1) % 2][i] - prices[i]);
                    //max = Math.max(max, dp[kk % 2][i]);
                }
            }
            return dp[k % 2][prices.length - 1];
        }
    }
    
    private int quickSolution(int[] prices) {
        int profile = 0;
        for (int i = 1; i < prices.length; i ++) {
            if (prices[i] > prices[i - 1]) {
                profile += prices[i] - prices[i - 1];
            }
        }
        return profile;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值