The title
Given an array, its ith element is the price of a given stock on the ith day.
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: [7,1,5,3,6,4] Output: 7 Explanation: If you buy on day 2 (stock price = 1) and sell on day 3 (stock price = 5), the exchange 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: Input: [1,2,3,4,5] Output: 4 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're doing multiple trades at once, you have to sell your shares before you can buy them 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.Copy the code
Tip:
1 <= prices.length <= 3 * 10 ^ 4
0 <= prices[i] <= 10 ^ 4
Their thinking
class Solution:
def maxProfit(self, prices:[int]) -> int:
lenP = len(prices)
i = 0
profit = 0
while i < lenP-1:
if prices[i]< prices[i+1]:
# The last one is higher than the previous one, there is profit, and then accumulate
profit += prices[i+1]-prices[i]
i += 1
return profit
Copy the code