diff --git a/Top150Interview/121BestTimetoBuyandSellStock.py b/Top150Interview/121BestTimetoBuyandSellStock.py index c68b4cf..e774a92 100644 --- a/Top150Interview/121BestTimetoBuyandSellStock.py +++ b/Top150Interview/121BestTimetoBuyandSellStock.py @@ -3,17 +3,42 @@ def maxProfit(prices): :type prices: List[int] :rtype: int """ - lowest = min(prices) - if lowest == prices[len(prices)-1]: - print('no profit') - return 0 - for i in range(len(prices)): - if lowest == prices[i]: - k = i+1 - # print(f'k is {k}') - profit = max(prices[k:]) - lowest - print(profit) - return profit + # Use iterative loop to look for the greatest profit, not the only profit after the lowest + # lowest = min(prices) + # if lowest == prices[len(prices)-1]: + # print('no profit') + # return 0 + # for i in range(len(prices)): + # if lowest == prices[i]: + # k = i+1 + # # print(f'k is {k}') + # profit = max(prices[k:]) - lowest + # 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,6,4,3,1]) \ No newline at end of file +maxProfit([7,6,4,3,1]) +# maxProfit([2,4,1]) \ No newline at end of file