Skip to content

Commit 982bc27

Browse files
kosuri-indupre-commit-ci[bot]cclauss
authored
add : Best time to buy and sell stock program under GREEDY methods (#10114)
* to add best_time_stock program * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update best_time_to_buy_and_sell_stock.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent e89ae55 commit 982bc27

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Given a list of stock prices calculate the maximum profit that can be made from a
3+
single buy and sell of one share of stock. We only allowed to complete one buy
4+
transaction and one sell transaction but must buy before we sell.
5+
6+
Example : prices = [7, 1, 5, 3, 6, 4]
7+
max_profit will return 5 - which is by buying at price 1 and selling at price 6.
8+
9+
This problem can be solved using the concept of "GREEDY ALGORITHM".
10+
11+
We iterate over the price array once, keeping track of the lowest price point
12+
(buy) and the maximum profit we can get at each point. The greedy choice at each point
13+
is to either buy at the current price if it's less than our current buying price, or
14+
sell at the current price if the profit is more than our current maximum profit.
15+
"""
16+
17+
18+
def max_profit(prices: list[int]) -> int:
19+
"""
20+
>>> max_profit([7, 1, 5, 3, 6, 4])
21+
5
22+
>>> max_profit([7, 6, 4, 3, 1])
23+
0
24+
"""
25+
if not prices:
26+
return 0
27+
28+
min_price = prices[0]
29+
max_profit: int = 0
30+
31+
for price in prices:
32+
min_price = min(price, min_price)
33+
max_profit = max(price - min_price, max_profit)
34+
35+
return max_profit
36+
37+
38+
if __name__ == "__main__":
39+
import doctest
40+
41+
doctest.testmod()
42+
print(max_profit([7, 1, 5, 3, 6, 4]))

0 commit comments

Comments
 (0)