Skip to content

Commit 96fe8d5

Browse files
committed
Added Stock Buy and Sell (Max One Transaction) solution in Python
1 parent a71618f commit 96fe8d5

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# ---------------------------------------------------------------
2+
# Title: Stock Buy and Sell - Max One Transaction Allowed
3+
#
4+
# Problem:
5+
# Given an array prices[] representing the price of a stock on each day,
6+
# find the maximum profit achievable by performing at most one transaction.
7+
# (You must buy before you sell.)
8+
#
9+
# Example:
10+
# Input: prices = [7, 10, 1, 3, 6, 9, 2]
11+
# Output: 8 (Buy at 1, Sell at 9)
12+
#
13+
# Approach:
14+
# We traverse the list once, keeping track of:
15+
# - min_price_so_far: The lowest price encountered so far.
16+
# - max_profit: The maximum profit seen so far.
17+
#
18+
# For each price:
19+
# - Compute potential profit = current_price - min_price_so_far.
20+
# - Update max_profit if this profit is greater than the previous.
21+
# - Update min_price_so_far if a smaller price is found.
22+
#
23+
# Time Complexity: O(n)
24+
# Space Complexity: O(1)
25+
# ---------------------------------------------------------------
26+
27+
def max_profit(prices):
28+
"""
29+
Calculate maximum profit from at most one buy-sell transaction.
30+
31+
Parameters:
32+
prices (list[int]): List of stock prices per day.
33+
34+
Returns:
35+
int: Maximum profit possible. Returns 0 if no profit is possible.
36+
"""
37+
38+
# Edge case: no transaction possible if list is too short
39+
if not prices or len(prices) < 2:
40+
return 0
41+
42+
# Initialize minimum price as the first day's price
43+
min_price_so_far = prices[0]
44+
45+
# Initialize maximum profit
46+
max_profit = 0
47+
48+
# Traverse price list starting from the second day
49+
for price in prices[1:]:
50+
# Update the minimum price seen so far
51+
min_price_so_far = min(min_price_so_far, price)
52+
53+
# Calculate today's potential profit
54+
profit_today = price - min_price_so_far
55+
56+
# Update max profit if today's profit is higher
57+
max_profit = max(max_profit, profit_today)
58+
59+
return max_profit
60+
61+
62+
# ---------------------------------------------------------------
63+
# Example Usage (For quick testing)
64+
# ---------------------------------------------------------------
65+
if __name__ == "__main__":
66+
prices = [7, 10, 1, 3, 6, 9, 2]
67+
print("Stock Prices:", prices)
68+
print("Maximum Profit:", max_profit(prices)) # Expected Output: 8

0 commit comments

Comments
 (0)