diff --git a/src/my_project/interviews/top_150_questions_round_23/ex_08_best_time_to_sell_stocks_ii.py b/src/my_project/interviews/top_150_questions_round_23/ex_08_best_time_to_sell_stocks_ii.py new file mode 100644 index 00000000..0de5446b --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_23/ex_08_best_time_to_sell_stocks_ii.py @@ -0,0 +1,25 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + + i = 0 + peak = None + valley = None + len_prices = len(prices) + result = 0 + + while i < len(prices) - 1: + + while i < len_prices - 1 and prices[i] >= prices[i+1]: + i += 1 + valley = prices[i] + + while i < len_prices - 1 and prices[i] <= prices[i+1]: + i += 1 + peak = prices[i] + + result += peak - valley + + return result diff --git a/src/my_project/interviews_typescript/top_150_questions_round_23/ex_08_best_time_to_sell_stocks_ii.ts b/src/my_project/interviews_typescript/top_150_questions_round_23/ex_08_best_time_to_sell_stocks_ii.ts new file mode 100644 index 00000000..60e507e5 --- /dev/null +++ b/src/my_project/interviews_typescript/top_150_questions_round_23/ex_08_best_time_to_sell_stocks_ii.ts @@ -0,0 +1,23 @@ +function maxProfit(prices: number[]): number { + let i = 0; + let peak = 0; + let valley = 0; + const lenPrices = prices.length; + let result = 0; + + while (i < lenPrices - 1) { + while (i < lenPrices - 1 && prices[i] >= prices[i + 1]) { + i++; + } + valley = prices[i]; + + while (i < lenPrices - 1 && prices[i] <= prices[i + 1]) { + i++; + } + peak = prices[i]; + + result += peak - valley; + } + + return result; +}; diff --git a/tests/test_150_questions_round_23/test_08_best_time_to_sell_stocks_ii_round_23.py b/tests/test_150_questions_round_23/test_08_best_time_to_sell_stocks_ii_round_23.py new file mode 100644 index 00000000..dbd3a8dc --- /dev/null +++ b/tests/test_150_questions_round_23/test_08_best_time_to_sell_stocks_ii_round_23.py @@ -0,0 +1,13 @@ +import unittest +import unittest +from src.my_project.interviews.top_150_questions_round_23\ +.ex_08_best_time_to_sell_stocks_ii 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 = 7 + self.assertEqual(output, target) \ No newline at end of file