leetcode | January 13, 2022
Problem
Given an array
prices
whereprices[i]
is the price of a given stock on theith
day,
return the maximum profit. If you cannot achieve any profit, return 0.
Make sure you should buy first and sell next.
Time Limit Exceeded
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
for i in range(len(prices) - 1):
for j in range(i+1, len(prices)):
profit = prices[j] - prices[i]
if profit > max_profit:
max_profit = profit
return max_profit
Time Limit Exceeded
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
for i in range(len(prices) - 1):
max_sell = max(prices[i+1:])
profit = max_sell - prices[i]
if profit > max_profit:
max_profit = profit
return max_profit
Memory: 25.2 MB
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit, min_price = 0, float("inf")
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit