3.2 The best time to buy and sell stocks (2)

3.2 The best time to buy and sell stocks

topic

Given an array, the i-th element is the price of the i-th day of a given stock.
Design an algorithm to calculate the maximum profit you can get. You can complete as many transactions as possible (buying a stock multiple times).
Note: You cannot participate in multiple transactions at the same time (you must sell the previous stock before buying again)

Examples

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on the 2nd day (stock price = 1), sell on the 3rd day (stock price = 5), This exchange can make a profit = 5-1 = 4.
Then, when buying on the 4th day (stock price = 3) and selling on the 5th day (stock price = 6), the exchange can make a profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on the first day (stock price = 1), sell on the fifth day (stock price = 5), this sum The exchange can make a profit = 5-1 = 4.
Note that you cannot buy stocks one after the other on day 1 and then sell them later.
Because this is involved in multiple transactions at the same time, you must sell the previous stock before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is completed, so the maximum profit is 0.

c ++ algorithm code

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

operation result

Insert picture description here

Published 22 original articles · praised 0 · visits 300

Guess you like

Origin blog.csdn.net/qq_45950904/article/details/104725221