The title

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

No.121 means you can buy and sell once. No.122 means you can buy and sell many times to maximize your profits

Train of thought

No.121

  1. Traverse the trading days to find the lowest point, record the difference between the following trading days and the lowest point, and record the maximum difference;
  2. If there is a lower date in the subsequent trading day, the lowest point is reset and step 1 is repeated.

No.122

  1. Go through the trading days and record yesterday’s trading volume. If today’s trading volume is greater than yesterday’s, the revenue increases
// No.122
var maxProfit = function(prices) {
    var lastPrice = Infinity;
    var res = 0;

    for (let i = 0; i < prices.length; i++) {
        if (prices[i] > lastPrice) {
            res += prices[i] - lastPrice
        }
        lastPrice = prices[i];
    }
    return res;
}
Copy the code