E-NR121. Best Time to Buy and Sell Stock
# 0 O(n), O(1) - > TLE
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit=float('-inf')
for buy in range(0, len(prices)):
for sell in range(buy+1, len(prices)):
cur_profit = prices[sell] - prices[buy]
max_profit = cur_profit if cur_profit > max_profit else max_profit
return max_profit if max_profit > 0 else 0
# 1 之后在研究,...先搁置一下, 先把tree的题目解决了
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) < 2:
return 0
maxProfit = 0;
curMin = prices[0];
for i in range(1,len(prices)):
curMin = min(curMin, prices[i]);
print('curMin: '+str(curMin))
print('i: '+str(i))
print('prices[i]: '+str(prices[i]))
maxProfit = max(maxProfit, prices[i] - curMin);
print('maxProfit: '+str(maxProfit))
print('---------')
return maxProfit;
Last updated
Was this helpful?