The best time to Buy and sell stocks II:

Given an array prices, prices[I] is the price of a given stock on day I. Design an algorithm to calculate the maximum profit you can make. You can make as many trades (buying and selling a stock multiple times) as possible.

Note: You can’t participate in more than one transaction at a time (you must sell your previous shares before buying again). Example 1: Input: prices = [7,1,5,3,6,4] Output: 7 Explanation: If you buy on the second day (stock price = 1) and sell on the third day (stock price = 5), this transaction will make a profit = 5-1 = 4. Then, by buying on day 4 (stock price = 3) and selling on day 5 (stock price = 6), the exchange makes a profit = 6-3 = 3.

Example 2: enter: prices = [1,2,3,4,5]

Explanation: If you buy on day 1 (stock price = 1) and sell on day 5 (stock price = 5), the exchange will make a profit = 5-1 = 4. Note that you can’t buy stocks on day 1 and day 2 and then sell them later. Because you are involved in multiple transactions at the same time, you have to sell your shares before you can buy them again.

Example 3: input: prices = [7,6,4,3,1] output: 0 explanation: in this case, no transaction is completed, so the maximum profit is 0. 1 <= prices. Length <= 3 * 104 0 <= prices[I] <= 104

The original

Their thinking

Stocks buy high and sell low, so make a judgment that if tomorrow’s stock is higher than today’s sell it, otherwise don’t do it.

See also useful dynamic programming, but I am not familiar with dynamic programming, not to mention this method.

steps

  • Iterate through the array and declare a variable that records total profitsum
  • Judge the stock price of the next day, if the next day is higher than the previous day, sell it, that is, the price of the next day minus the price of the previous day, add up the price.
  • Return total profit

1 <= prices.length <= 3 * 104

code

JavaScript

var maxProfit = function(prices){
	let sum = 0;
	for(let day = 0; day < prices.length; day++){
		if(prices[day + 1] > prices[day]){
			sum += prices[day + 1] - prices[day]
		}
	}
	return sum;
}
Copy the code

Optimization idea

No.