Leetcode Problem solving best time to Buy and Sell Stock II original title
Given the daily stock price, if you allow multiple trades, you can buy and sell multiple times, but only one stock is held at most, and when you buy again, you must sell the previous stock for the maximum profit you can get.
Note the point:
Example:
Input: Prices = [2, 4, 6, 1, 3, 8, 3]
Output: 11 ([2,6], [1,8] is the time to buy and sell two times)
Thinking of solving problems
Multiple trades can be made, in order to obtain the most profit, should buy at the beginning of the interval of each price rise, sell at the end. Iterate over the array before, and if the price goes down, sell it the day before and buy it again on the date of the fall. Do not forget that there is no downside after the last ascent and add extra.
AC Source
class solution(object): def maxprofit(self, prices): "" : Type Prices:list[int]: Rtype:int " " " if notPrices:return 0Low = High = prices[0] Profit =0 forIinchRange1, Len (prices)):ifPrices[i] >= prices[i-1]: High = prices[i]Else: Profit + = high-low Low = high = Prices[i] Profit + = high-lowreturnProfitif__name__ = ="__main__":assertSolution (). Maxprofit ([2,4,6,1,3,8,3]) == One
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode best time to Buy and Sell Stock II