From 28756b2803fa2c1e302df014f89fd15d283a40ed Mon Sep 17 00:00:00 2001 From: ivan Date: Wed, 24 Sep 2025 04:27:03 -0600 Subject: [PATCH] adding algo --- .../best_time_to_buy_stock.py | 19 +++++++++++++++++++ .../test_best_time_to_buy_stock_round_20.py | 11 +++++++++++ 2 files changed, 30 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_20/best_time_to_buy_stock.py create mode 100644 tests/test_150_questions_round_20/test_best_time_to_buy_stock_round_20.py diff --git a/src/my_project/interviews/top_150_questions_round_20/best_time_to_buy_stock.py b/src/my_project/interviews/top_150_questions_round_20/best_time_to_buy_stock.py new file mode 100644 index 00000000..0e2dd295 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_20/best_time_to_buy_stock.py @@ -0,0 +1,19 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod +import math + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + + min_price = math.inf + max_profit = 0 + len_prices = len(prices) + + for i in range(len_prices): + + if prices[i] < min_price: + min_price = prices[i] + elif prices[i] - min_price > max_profit: + max_profit = prices[i] - min_price + + return max_profit diff --git a/tests/test_150_questions_round_20/test_best_time_to_buy_stock_round_20.py b/tests/test_150_questions_round_20/test_best_time_to_buy_stock_round_20.py new file mode 100644 index 00000000..5d5c5cd3 --- /dev/null +++ b/tests/test_150_questions_round_20/test_best_time_to_buy_stock_round_20.py @@ -0,0 +1,11 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_20\ +.best_time_to_buy_stock import Solution + +class BestTimeToSellStockTestCase(unittest.TestCase): + + def test_best_time_to_sell_stock(self): + solution = Solution() + output = solution.maxProfit(prices=[7,1,5,3,6,4]) + target = 5 + self.assertEqual(output, target) \ No newline at end of file