- 买卖股票的最佳时机I
法一:
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
maxdiff = 0
for i in range(len(prices)):
temp = 0
for j in range(i+1,len(prices)):
temp = prices[j] - prices[i]
if temp > maxdiff:
maxdiff = temp
return maxdiff
注:超出了时间限制
法二:
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
minprice = prices[0]
profit = 0
for i in prices:
minprice = min(i, minprice)
profit = max(i - minprice, profit)
return profit
- 买卖股票的最佳时机II
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i-1]:
profit += prices[i] - prices[i-1]
return profit