From 59f81a89e3a0b7a8bf858fef5876a5716388ccf0 Mon Sep 17 00:00:00 2001 From: Ilya Nikokoshev Date: Thu, 26 May 2022 01:16:55 +0200 Subject: [PATCH] Add LC 354 --- lc_0354_envelopes.py | 46 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 lc_0354_envelopes.py diff --git a/lc_0354_envelopes.py b/lc_0354_envelopes.py new file mode 100644 index 0000000..f0394f7 --- /dev/null +++ b/lc_0354_envelopes.py @@ -0,0 +1,46 @@ +from bisect import bisect_left +from typing import List +import unittest + + +class SolutionShort: + def maxEnvelopes(self, envelopes: List[List[int]]) -> int: + m = [float("inf")] * len(envelopes) + for _, h in sorted(envelopes, key=lambda x: (x[0], -x[1])): + m[bisect_left(m, h)] = h + return sum(v < float("inf") for v in m) + + +def set_val(a, v, i): + a[i:i + 1] = [v] + + +class SolutionReadable: + def maxEnvelopes(self, envelopes: List[List[int]]) -> int: + m = [] + for _, h in sorted(envelopes, key=lambda x: (x[0], -x[1])): + set_val(m, h, bisect_left(m, h)) + return len(m) + + +# noinspection PyMethodMayBeStatic +class MyTestCase(unittest.TestCase): + def setUp(self) -> None: + self.solutions = [SolutionShort(), SolutionReadable()] + + def test_examples(self): + for solution in self.solutions: + assert solution.maxEnvelopes([[5,4],[6,4],[6,7],[2,3]]) == 3 + assert solution.maxEnvelopes([[1,1],[1,1],[1,1]]) == 1 + + def test_simple(self): + for solution in self.solutions: + assert solution.maxEnvelopes([[3,5]]) == 1 + + def test_complex(self): + for solution in self.solutions: + assert solution.maxEnvelopes([[100,50],[80, 60], [30, 30], [50,100]]) == 2 + + +if __name__ == "__main__": + unittest.main()