[LeetCode] 122. 买卖股票的最佳时机ii best-time-to-buy-and-sell-stock-ii(贪心算法)

2023-05-28,,

思路:

只要第二天的价格高于第一天,就进行交易。(这样的话就默认可以同一天内先卖出再买进)

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profit=0
for i in range(0,len(prices)-1):
temp=prices[i+1]-prices[i]
if temp>0:
profit += temp
return profit

复杂度分析:

时间复杂度:O(n),遍历一次。
空间复杂度:O(1),需要额外的常量空间。

不过这种方法虽然简单,但只有遍历,感觉没有用到贪心的精髓,毕竟实际上不可能提前就知道第二天的股票价格。

[LeetCode] 122. 买卖股票的最佳时机ii best-time-to-buy-and-sell-stock-ii(贪心算法)的相关教程结束。

《[LeetCode] 122. 买卖股票的最佳时机ii best-time-to-buy-and-sell-stock-ii(贪心算法).doc》

下载本文的Word格式文档,以方便收藏与打印。