DP
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
else:
rmax = 0
pmin = prices[0]
for i in range(len(prices)):
if prices[i] <= pmin:
pmin = prices[i]
if rmax <= prices[i] - pmin:
rmax = prices[i] - pmin
return rmax
暴力法会超时
class Solution:
def maxProfit(self, prices: List[int]) -> int:
rmax = 0
for i in range(len(prices)):
for j in range(i,len(prices)):
if prices[j] >= prices[i]:
rmax = max(rmax,prices[j] - prices[i])
return rmax