This Python code is a solution to the well-known "Best...
May 18, 2025 at 06:32 AM
This Python code is a solution to the well-known "Best Time to Buy and Sell Stock" problem (often presented in coding interviews such as on LeetCode).
What It Does:
The code calculates the maximum profit you can achieve by buying and selling a stock, given an array of stock prices (prices
) where the ( i )-th element represents the stock price on day ( i ). You are only allowed to make one buy and one sell (no multiple transactions or shorting).
Explanation of the Code:
-
Variables:
min_price
: Keeps track of the lowest stock price seen so far as you iterate through the prices. It starts as infinity (float('inf')
), because initially we haven't seen any price.max_profit
: Stores the maximum profit possible so far. It starts at 0 because the maximum profit at the beginning is zero.
-
Logic (Loop through
prices
):- For each price in the
prices
array:- Check for a new minimum price: If the current price is less than
min_price
, updatemin_price
to be this price. This simulates buying the stock at the lowest price seen. - Update the maximum profit: If the current price is greater than the
min_price
, calculate the potential profit (price - min_price
) and updatemax_profit
if this profit is larger than the value currently stored inmax_profit
.
- Check for a new minimum price: If the current price is less than
- For each price in the
-
Result:
- After the loop,
max_profit
contains the highest profit possible from one buy-sell transaction.
- After the loop,
Example Walkthrough:
Input:
prices = [7, 1, 5, 3, 6, 4]
- Day 1: price = 7
min_price
= 7,max_profit
= 0 (no profit yet)
- Day 2: price = 1
min_price
= 1 (new minimum),max_profit
= 0
- Day 3: price = 5
- Profit = ( 5 - 1 = 4 ), update
max_profit
to 4
- Profit = ( 5 - 1 = 4 ), update
- Day 4: price = 3
- Profit = ( 3 - 1 = 2 ),
max_profit
remains 4
- Profit = ( 3 - 1 = 2 ),
- Day 5: price = 6
- Profit = ( 6 - 1 = 5 ), update
max_profit
to 5
- Profit = ( 6 - 1 = 5 ), update
- Day 6: price = 4
- Profit = ( 4 - 1 = 3 ),
max_profit
remains 5
- Profit = ( 4 - 1 = 3 ),
Output:
max_profit = 5
Edge Cases:
-
Empty Prices (
prices = []
):- The loop does not execute, so the function returns
max_profit = 0
.
- The loop does not execute, so the function returns
-
One Price (
prices = [5]
):- No transactions are possible, so the profit is 0.
-
Prices Always Decreasing (
prices = [7, 6, 5, 4]
):- The minimum price keeps decreasing, but no profitable transaction can be made, so profit remains 0.
Overall Complexity:
- Time Complexity: ( O(n) ), where ( n ) is the length of the
prices
array (only one pass is made through the array). - Space Complexity: ( O(1) ), as only a few variables are used (no additional data structures).
Generate your own explanations
Download our vscode extension
Read other generated explanations
Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node