Skip to content

Commit

Permalink
feature: best time to buy and sell stock lambda
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Nov 21, 2023
1 parent 359648c commit 096b09b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 6 additions & 0 deletions dynamic_programming/BestTimeToBuyAndSellStock.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from functools import reduce
from typing import List


Expand All @@ -11,3 +12,8 @@ def max_profit(self, prices: List[int]) -> int:
res = max(res, price - min_price)

return res


# O(n) time || O(1) space
def max_profit_lambda(self, prices: List[int]) -> int:
return reduce(lambda acc, price: (min(acc[0], price), max(acc[1], price - acc[0])), prices[1:], (prices[0], 0))[1]
4 changes: 3 additions & 1 deletion dynamic_programming/test/test_max_profit.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import unittest

from dynamic_programming.BestTimeToBuyAndSellStock import max_profit
from dynamic_programming.BestTimeToBuyAndSellStock import max_profit, max_profit_lambda


class MyTestCase(unittest.TestCase):
def test_max_profit(self):
self.assertEqual(5, max_profit(self, [7, 1, 5, 3, 6, 4]))
self.assertEqual(5, max_profit_lambda(self, [7, 1, 5, 3, 6, 4]))

def test_max_profit_1(self):
self.assertEqual(0, max_profit(self, [7, 6, 4, 3, 1]))
self.assertEqual(0, max_profit_lambda(self, [7, 6, 4, 3, 1]))


if __name__ == '__main__':
Expand Down

0 comments on commit 096b09b

Please sign in to comment.