题目描述
自己解法
采取的方法是计算折线图的每个上升区段,将峰值与低谷值相减得到每个上升区段的利润,最后进行累加,类似于官方题解中的第二种解法。时间复杂度
O
(
n
)
O(n)
O(n),空间复杂度
O
(
1
)
O(1)
O(1)。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
ans = 0
start,end = 0,1
length = len(prices)
while end < length:
if prices[start] >= prices[end]:
start += 1
end += 1
else:
temp = start + 1
end += 1
while end < length:
if prices[temp] <= prices[end]:
temp += 1
end += 1
else:
break
ans += prices[temp] - prices[start]
start = end
end += 1
return ans
后续改进:峰谷法还是不够简练和优化,参考官方题解中的第三种解法,无需找到特定的“峰谷”,只要元素前后保持递增关系,就表示可以获得利润。时间复杂度
O
(
n
)
O(n)
O(n),空间复杂度
O
(
1
)
O(1)
O(1)。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
ans = 0
for i in range(1,len(prices)):
if prices[i] > prices[i-1]:
ans += prices[i] - prices[i-1]
return ans
官方题解
题解区网友
暴力搜索和动态规划的解法,参考:暴力搜索、贪心算法、动态规划。