From 07a918bcb07a1b6e073508eb23aebba631467be9 Mon Sep 17 00:00:00 2001 From: ImAlpha Date: Tue, 27 Jun 2023 01:46:40 -0700 Subject: [PATCH] Update Lesson on Dynamic min/max --- Top150Interview/LessonsLearned.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Top150Interview/LessonsLearned.md b/Top150Interview/LessonsLearned.md index b6f5404..ee24697 100644 --- a/Top150Interview/LessonsLearned.md +++ b/Top150Interview/LessonsLearned.md @@ -14,4 +14,18 @@ shifted_negative = my_list[2:] + my_list[:2] print(shifted_negative) # Output: [3, 4, 5, 1, 2] ``` -- \ No newline at end of file +## Dynamically Updating a value in a Single Pass + +``` +# 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 +``` \ No newline at end of file