Best Time to Buy and Sell Stock IV - LeetCode

Best Time to Buy and Sell Stock IV - LeetCode

题目
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.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


又找了一道动态规划的题目做。
本来想用一个三维数组a[i][k][f]来记录前i天交易k次所能获得的最大利润,交易有可能出现半次(只买入而还未卖出),所以数组后面加了一维,a[i][k][1]表示前i天交易k-1次,外加买入一次所能获得的最大利润,a[i][k][0]表示前i天交易k次(并且全部卖出)所能获得的最大利润。

当我们知道了前n天的情况,要计算前n+1天时,可以由以下公式推导:

cur = prices[n+1] //今天的价格
a[n+1][k][0] = max(a[n][k][1]+cur, a[n][k][0])
a[n+1][k][1] = max(a[n][k-1][0]-cur, a[n][k][1])

这里有一个问题,数据太大的时候需要一个很大的数组,栈的空间有可能不够(事实上是有不够的时候的),这时就需要优化一下。
注意到当a[i]这一层计算完之后,他们的值就不会再改变了,而计算a[i+1]这一层只需要用到a[i]这一层的值,所以当我们计算完a[i+1]这一层之后,可以覆盖掉a[i]这一层的值,这样就不用另外的存储空间了(实际写代码的时候可以一边计算,一边覆盖)。

下面是代码

class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        int len = prices.size();
        if (len < 2) return 0;
        if (k>len/2){
            int ans = 0;
            for (int i=1; i<len; ++i){
                ans += max(prices[i] - prices[i-1],0);
            }
            return ans;
        }
        int profit[k+1][2] = {0};
        profit[0][0] = 0;
        profit[0][1] = 0;
        for (int i = 1; i <= k; i++) {
            profit[i][0] = 0;
            profit[i][1] = -prices[0];
        }
        int i, j;
        for (i = 1; i < len; i++) {
            int price = prices[i];
            for (j = 1; j <= k; j++) {
                profit[j][0] = (profit[j][1]+price)>profit[j][0]?(profit[j][1]+price):profit[j][0];
                profit[j][1] = (profit[j-1][0]-price)>profit[j][1]?(profit[j-1][0]-price):profit[j][1];
            }
        }
        return profit[k][0];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值