Skip to content

Commit

Permalink
feature: best time to buy and sell stock ii lambda
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Nov 21, 2023
1 parent 5b4ef5a commit 359648c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
6 changes: 6 additions & 0 deletions dynamic_programming/BestTimeToBuyAndSellStockII.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 @@ -9,3 +10,8 @@ def max_profit(self, prices: List[int]) -> int:
res += prices[i] - prices[i - 1]

return res


# O(n) time || O(1) space
def max_profit_lambda(self, prices: List[int]) -> int:
return reduce(lambda profit, i: profit + max(prices[i] - prices[i - 1], 0), range(1, len(prices)), 0)
5 changes: 4 additions & 1 deletion dynamic_programming/test/test_max_profit_ii.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import unittest

from dynamic_programming.BestTimeToBuyAndSellStockII import max_profit
from dynamic_programming.BestTimeToBuyAndSellStockII import max_profit, max_profit_lambda


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

def test_max_profit_1(self):
self.assertEqual(4, max_profit(self, [1, 2, 3, 4, 5]))
self.assertEqual(4, max_profit_lambda(self, [1, 2, 3, 4, 5]))

def test_max_profit_2(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 359648c

Please sign in to comment.