122. Best Time to Buy and Sell Stock II

Problem:

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 (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

思路1
将这个问题转化成求单调增的子串问题,然后求出右边界与左边界的差值即得到这个子串的最大利润,然后将所有这种子串的利润之和相加即得到最大利润。因为如果子串内有数比之前的小,那么可以以这个数为界,将其分成2个子串,得到的新的利润之和是肯定比之前这个子串的利润和大的。所以算法的思路就是一直在寻找单调增长子串的右边界,然后再以右边界的下一个数为起点寻找新的单调递增子串。

Solution I:

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

性能
Runtime: 12 ms  Memory Usage: 9.6 MB

思路2
这个思路更简单,就是碰到股票价格高的立马卖,一直买一直卖。这样应该重复运算了很多次,按道理是比思路1的运算多很多的,结果最后的时间复杂度小很多,不太理解。

Solution II:

int maxProfit(vector<int>& prices) {
    if (!prices.size())  return 0;
    int max = 0;
    for (int i = 0; i < prices.size() -1; i++) {
        if (prices[i+1] > prices[i])    max += prices[i+1] - prices[i];
    }
    return max;
}

性能
Runtime: 4 ms  Memory Usage: 9.6 MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12262817.html