Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note: that you cannot sell a stock before you buy one.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
min_price = max(prices)
max_profit = 0
for i in range(len(prices)):
if prices[i] < min_price:
min_price = prices[i]
profit = prices[i] - min_price
if profit > max_profit:
max_profit = profit
return max_profit
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
for i in range(len(prices)):
for j in range(i+1,len(prices)):
profit = prices[j] - prices[i]
if profit > max_profit:
max_profit = profit
return max_profit