Update min price and max profit dynamically

This commit is contained in:
Jacob Delgado 2023-06-27 01:44:19 -07:00
parent dbc1ffca8b
commit ad4165f35e

View File

@ -3,17 +3,42 @@ def maxProfit(prices):
:type prices: List[int] :type prices: List[int]
:rtype: int :rtype: int
""" """
lowest = min(prices) # Use iterative loop to look for the greatest profit, not the only profit after the lowest
if lowest == prices[len(prices)-1]: # lowest = min(prices)
print('no profit') # if lowest == prices[len(prices)-1]:
return 0 # print('no profit')
for i in range(len(prices)): # return 0
if lowest == prices[i]: # for i in range(len(prices)):
k = i+1 # if lowest == prices[i]:
# print(f'k is {k}') # k = i+1
profit = max(prices[k:]) - lowest # # print(f'k is {k}')
print(profit) # profit = max(prices[k:]) - lowest
return profit # print(profit)
# return profit
# Code Timed out
# profit = []
# for i in range(len(prices)):
# for j in range(i+1, len(prices)):
# if prices[i] < prices[j]:
# profit.append(prices[j] - prices[i])
# # print(max(profit))
# if not profit:
# return 0
# return max(profit)
# Code with faster Implementation
min_price = prices[0] # Track the minimum price seen so far
max_profit = 0 # Track the maximum profit
for price in prices:
# print(f'price is {price}')
# print(f'MinPrice: {min_price} or {price}')
# print(f'MaxProfit: {max_profit} or [{price} - {min_price} = {max(max_profit, price - min_price)}]')
min_price = min(min_price, price) # Update the minimum price
max_profit = max(max_profit, price - min_price) # Update the maximum profit
return max_profit
# maxProfit([7,1,5,3,6,4]) # maxProfit([7,1,5,3,6,4])
maxProfit([7,6,4,3,1]) maxProfit([7,6,4,3,1])
# maxProfit([2,4,1])