Tencent 48-the best time to buy and sell stocks II leetcode122
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).
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.
- Can trade multiple times, but each transaction is still bought before sold
- With greedy ideas, every time you look for troughs and crests, two adjacent troughs and crests are used as a transaction to accumulate income
- One thing to note is the boundary conditions. All judgments use the equal sign, which may lead to invalid sales signals, which need to be solved by the validity of a price_buy_flag buy signal, that is, there must be a valid buy signal before selling
- Otherwise, two of 6 in [5, 2, 3, 6, 6, 2, 9, 10, 7, 4, 5, 0] will be considered as selling signals.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
##可以多次交易,但每次交易仍是先买后卖的
##用贪心的思路,每次寻找波谷和波峰,相邻两次波谷和波峰作为一次交易,累加收入
##注意的一个是边界条件,判断时全用了带等号的,这就可能导致出现无效的卖信号,需要通过一个price_buy_flag买信号的有效性来解决,即在卖之前必须有有效的买信号
##否则对【5,2,3,6,6,2,9,10,7,4,5,0】其中的两个6都会认为是卖信号
# if len(prices)==0 or len(prices)==1:return 0
# else:
# res=0
# price_buy_flag=False
# for i in range(0,len(prices)):
# if (i!=0 and i!=len(prices)-1 and prices[i-1]>=prices[i] and prices[i+1]>=prices[i]) or (i==0 and prices[i+1]>=prices[i]) :
# price_buy=prices[i]
# price_buy_flag=True
# if (i!=0 and i!=len(prices)-1 and prices[i-1]<=prices[i] and prices[i+1]<=prices[i]) or (i==len(prices)-1 and prices[i-1]<=prices[i]):
# price_sale=prices[i]
# res+=price_sale-price_buy if price_buy_flag else 0
# price_buy_flag=False
# return res
maxprofit = 0
for i in range(1,len(prices)):
if (prices[i] > prices[i - 1]):
maxprofit += prices[i] - prices[i - 1]
return maxprofit
##原来波峰波谷之间的差值可以直接用连续的两两差值来累加