- 跟我一起刷leetCode算法题9之Best Time to B
- 【2019-07-30】leetcode(121-130)
- 【leetcode】122、Best Time to Buy a
- LeetCode #122: Best Time to Buy
- Leetcode 122 Best time to buy an
- Leetcode PHP题解--D109 122. Best T
- leetcode:122. Best Time to Buy a
- [数组]122. Best Time to Buy and Se
- Leetcode122-Best Time to Buy and
- Best Time to Buy and Sell Stock
翻译
你有一个数组,其中第i个元素表示第i天的股票价格。设计一个算法以找到最大利润。你可以尽可能多的进行交易(例如,多次买入卖出股票)。然而,你不能在同一时间来多次交易。(例如,你必须在下一次买入前卖出)
price= 【4 7 8 2 8】
分析
最大利润是(8-4)+(8-2)=10
简单的思路是:只要后者比前者大,可以累积利润。(7-4)+(8-7)+(8-2)=10
price = [4,7,8,2,8]
def max_profix(price):
max_pro =0
for i in range(1,len(price)):
if price[i]>price[i-1]:
max_pro = max_pro + price[i]-price[i-1]
return max_pro
#return sum(max(prices[i+1]-price[i],0) for i in range(len(prices)-1))
print max_profix(price)
网友评论