Best time (ii) to buy stocks

Leecode brush title

  • Title Description

Given an array, which i-th element is a given stock i-day prices.
Design an algorithm to compute the maximum profit you can get. You can close more deals (buy and sell a stock) as much as possible.
Note: You can not simultaneously involved in multiple transactions (you must sell before buying shares again before the fall).

  • Examples

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Day 2 (= 1 stock price), when buying, on day 3 (stock price = 5) when sold, this transaction can profit = 5-1 = 4.
Then, on day 4 (stock price = 3) When buying on day 5 (stock price = 6), when sold, this transaction can profit = 6-3 = 3.

Enter: [1,2,3,4,5]
Output: 4
to explain: (stock price = 1) when buying on Day 1, on Day 5 (stock price = 5), when sold, this Exchange can profit = 5-1 = 4.
Note that you can not buy stock in a series of 1 and day 2, then after they are sold.
Because it belongs to the same time involved in multiple transactions, you have to sell the stock before the fall before buying again.

  • Code
/*对于每一天,需要决定进行什么操作,有且只有三种操作:买、卖或者什么都不做。
由于每次只能进行一次交易,所以又可以分为两种情况: 
1)当前手里没有股票。那么对于这一天就需要决定是否买入股票。
当后一天的股价高于当前股价时,就应该买入,因为买入肯定能收益。 
2)当前已经持有股票。那么对于这一天就需要决定是否卖出股票。
当后一天的股价低于或等于当前股价时,就应该卖出,因为不卖出的话收益会降低。 
对于最后一天,如果持有股票,应该卖出。*/
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty()) return 0;
        int profit = 0;
        bool to_buy = true;
        int current_price = 0;
        for(int i = 0; i < prices.size() - 1; i++) {
            if(to_buy) {
                if(prices[i + 1] > prices[i]) {
                    to_buy = false;
                    current_price = prices[i];
                }
            }
            else {
                if(prices[i + 1] <= prices[i]) {
                    to_buy = true;
                    profit += prices[i] - current_price;
                }
            }
        }
        if(!to_buy) profit += prices.back() - current_price;
        return profit;
    }
};

Guess you like

Origin blog.csdn.net/qq_42780025/article/details/91352761