122. Best Time to Buy and Sell Stock II

来源:互联网 发布:python for 一行 编辑:程序博客网 时间:2024/06/06 12:46

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).

这题之前还有个Best Time to Buy and Sell Stock I, 比较直观,那题直接建一个一维的dp, 存着从这个点之后,最大的是什么,就可以线性扫描每个点,得出,当以这个点为最小值的是侯的最大利润是多少,基于这个逻辑,我在这个不限次数的计算中同样用了dp的思想,代码如下:

int maxProfit(vector<int>& prices) {    int len = prices.size();    if (len < 2) return 0;    vector<int> dp(len + 1, 0);    for (int i = 2; i <= len; i++) {        int temp_max = dp[i - 1];        for (int j = 1; j <= i; j++) {            temp_max = max(dp[j - 1] + prices[i - 1] - prices[j - 1], temp_max);        }        dp[i] = temp_max;    }    return dp[len];}

算法复杂度O(n^2),直接超时,通过不了。

后来发现,这题考的不是什么典型算法问题,就是对具体问题的具体分析。找出基本规律。

思路一:peak and valley
这里写图片描述
你会发现,其实最终利润最大的情况其实就是每一个peak减去它的上一个valley,因为A+B > C,所以其实并不需要像我的解法一一样,那么多的变化,每一个都去check。具体问题往往有具体的先验可以分析。
代码:

int maxProfit(vector<int>& prices) {    int len = prices.size();    int maxprofit = 0;    if (len == 0) return maxprofit;    int valley = prices[0];    int peak = prices[0];    for (int i = 0; i < len - 1; i++) {        while (i < len - 1 && prices[i] > prices[i + 1]) i++;        valley = prices[i];        while (i < len - 1 && prices[i] < prices[i + 1]) i++;        peak = prices[i];        maxprofit += peak - valley;    }    return maxprofit;}

方法三:
方法二的变体,其实可以把代码写的更简单,不用去check每一个peak 和valley,peak和valley的difference就是每次递增的数值求和,所以所有的peak和valley的difference求和,其实就是对所有正增长的求和。

代码:

int maxProfit(vector<int>& prices) {    int len = prices.size();    int maxprofit = 0;    for (int i = 1; i < len; i++) {        if (prices[i] > prices[i - 1]) {            maxprofit += prices[i] - prices[i - 1];        }    }    return maxprofit;}
原创粉丝点击