122. Best Time to Buy and Sell Stock II

problem description

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.

algorithm thought

可以借助之前只能买一次的思想,只是这里是能买很多次。只要有利润,我们都加上。

首先对于下一天价格比今天低的情况,这时候我们肯定要下一天买而不是这一天高价买。也就是把买进的价格改成下一天的。

如果下一天的价格比今天高,我们直接把利润加上。但是如果之后价格持续走高,我们先不加利润,一直往后看,直到最高的价格,我们用最高的价格减去最低的价格,这是利润增益。

分析可以知道,价格走向只有上面两种,要不是一直递增,要不就是下降。这样就可以归纳成一般情况,写出代码.注意写成一般情况下时,要注意最后的状态,这里最后push一个INT_MIN,就能处理所有情况

code

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res=0;
        prices.push_back(INT_MIN);
        int base_index;
        for(int i=0;i<prices.size()-1;++i){
            base_index=i;
            while(prices[i]<=prices[i+1]){
                i++;
            }
            res+=(prices[i]-prices[base_index]);
        }
        return res;
    }
};

algorithm analysis

也是一次遍历数组,时间复杂度O(n)

Last updated