从分歧和征服方法中找到索引
我正在使用划分和征服方法练习的练习 https://leetcode.com/problems/bests/best -Time-to-to-buy and-sell-sell-sell-stock-iii/
def calcchanges(price):
changes = []
for i in range(len(price)-1):
delta = round(price[i+1] - price[i],3)
changes.append(delta)
return changes
def MSSDAC(A, low=0, high=None):
if high==None:
high = len(A)-1
if low==high:
if A[low]>0:
return A[low]
else:
return 0
mid = (low+high)//2
maxleft = MSSDAC(A, low, mid)
maxright = MSSDAC(A, mid+1, high)
maxleft2center = left2center = 0
for i in range(mid, low-1, -1):
left2center += A[i]
maxleft2center = max(left2center, maxleft2center)
maxright2center = right2center = 0
for i in range(mid+1, high+1):
right2center += A[i]
maxright2center = max(right2center, maxright2center)
return max(maxleft, maxright, maxleft2center+maxright2center)
#This code is only focusing on 1 transaction
""" Example 2
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
"""
prices = [1,2,3,4,5]
changes = calcchanges(prices)
maxprofit = MSSDAC(changes)
print(maxprofit)
我的问题是,有可能获得一天吗?,在第1天购买并在第5天出售?
通过使用Divide和Conquer,我将列表递归分配。因此,我有点迷失了如何跟踪索引。
Im practicing using divide and conquer approach using the practice from
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
def calcchanges(price):
changes = []
for i in range(len(price)-1):
delta = round(price[i+1] - price[i],3)
changes.append(delta)
return changes
def MSSDAC(A, low=0, high=None):
if high==None:
high = len(A)-1
if low==high:
if A[low]>0:
return A[low]
else:
return 0
mid = (low+high)//2
maxleft = MSSDAC(A, low, mid)
maxright = MSSDAC(A, mid+1, high)
maxleft2center = left2center = 0
for i in range(mid, low-1, -1):
left2center += A[i]
maxleft2center = max(left2center, maxleft2center)
maxright2center = right2center = 0
for i in range(mid+1, high+1):
right2center += A[i]
maxright2center = max(right2center, maxright2center)
return max(maxleft, maxright, maxleft2center+maxright2center)
#This code is only focusing on 1 transaction
""" Example 2
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
"""
prices = [1,2,3,4,5]
changes = calcchanges(prices)
maxprofit = MSSDAC(changes)
print(maxprofit)
My question would be, is it possible to get the day?, Buy on day 1 and sell on day 5?
By using divide and conquer I split the list recursively. Thus i'm kinda lost how to track the index.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论