[Leetcode][Dynamic programming] 121. Best time to buy and sell stock

53 篇文章 0 订阅
31 篇文章 0 订阅

Say you have an array for which the ith element is the price of a given stock on the day i.
If you were only permitted to complete only one transaction (i.e. buy one and sell one stock), design an algorithm to find the maximum profit.

我最初的设想是运用最原始的dynamic programming来解决这个问题,这个解决方案的时间和空间复杂度都是O(n^2) (需要n^2次循环和n^2大小的二维数组)。我的代码如下:

public class Solution {
    /**
     * Bottom-up approach
     * Profit(selldatelimit, buydatelimit) = max{Profit(selldate-1, buydate), Profit(selldate, buydate+1), p[selldate] - p[buydate]} this is the maximum profit we can get from the time range of buydatelimit to the selldatelimit
     * Profit(selldatelimit, buydatelimit) = 0 if selldate = buydate
     * Profit(selldatelimit, buydatelimit) doesn't exist if selldatelimit < buydatelimit
     * i = selldatelimit
     * j = buydatelimit
     * i >= j
     */
    public int maxProfit(int[] prices) {
        int l = prices.length;
        if (l == 0) {
            return 0;
        }
        int[][] profit = new int[l][l];
        for (int c = 0; c <= l - 1; c++) {
            for (int j = 0; j <= l - 1 - c; j++) {
                int i = j + c;
                if (i == j) {
                    profit[i][j] = 0; 
                    //buy and sell at the same day, profit is 0
                }
                else {
                    profit[i][j] = profit[i][j+1] > profit[i-1][j] ? profit[i][j+1] : profit[i-1][j];
                    profit[i][j] = profit[i][j] > (prices[i] - prices[j]) ? profit[i][j] : prices[i] - prices[j];
                    //profit[i][j] is the largest one among the three ones
                }
            }
        }

        return profit[l - 1][0]; 
        //return the largest profit we can get from the time range of the first day to the last day
    }
}

然而这个方法在提交的时候报错: Time Limit Exceeded. 报错的时候提示的输入数组是一个非常大的数组。

出错的原因很可能是因为O(n^2)的时间和空间复杂度导致的执行速度太慢超出了时间限制。所以我参考了discussion里的解法。总结出如下方法:
1. 因为此题的目的是求出在只能买卖一次的情况下如何获取最大利润,所以其根本目的是求出在prices[]数组中任意两个数据之间的差值的最大值。(当然卖出时间要大于买入时间)
2. 那么基本的想法就是如果prices[i] > prices[i-1],最大差值就应当是历史最优利润或者当前价格减去历史最低价格(max{profit, prices[i]-minimal_price})
如果prices[i] < prices[i-1],那么最大差值应当是历史最优利润,此时应当更新历史最低价格。

那么在这种情况下,程序应当如下:

public class Solution {
    public int maxProfit(int[] prices) {
        /**
         * basic idea:
         * Since we can only complete at most one transaction, we only need to find out the maximum interval between any two prices in side the prices array. 
         * So the largest profit must be the historical maximum interval until day N-1 or the interval between price of Day N and the historical minimum price.
         * Then we may have to renew the mimimum price or the maximum interval.
         */
        int l = prices.length;
        if (l == 0 || l == 1){
            return 0;
        }
        int minprice = prices[0];
        int maxprofit = 0;
        for (int i = 1; i < l; i ++){
            maxprofit = maxprofit > prices[i] - minprice ? maxprofit : prices[i] - minprice;
            minprice = minprice < prices[i] ? minprice : prices[i];
        }
        return maxprofit;
    }
}

其中的三元运算符起到判断大小的作用。此种方法对应的程序的时间复杂度为O(n)而空间复杂度为O(1)。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耀凯考前突击大师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值