|
| 1 | +""" |
| 2 | +You are given a 2D array of integers envelopes where |
| 3 | +envelopes[i] = [wi, hi] represents the width and the |
| 4 | +height of an envelope. |
| 5 | +
|
| 6 | +One envelope can fit into another if and only if both |
| 7 | +the width and height of one envelope are greater than |
| 8 | +the other envelope's width and height. |
| 9 | +
|
| 10 | +Return the maximum number of envelopes you can Russian |
| 11 | +doll (i.e., put one inside the other). |
| 12 | +
|
| 13 | +Note: You cannot rotate an envelope. |
| 14 | +
|
| 15 | +Example 1: |
| 16 | +Input: envelopes = [[5,4],[6,4],[6,7],[2,3]] |
| 17 | +Output: 3 |
| 18 | +Explanation: The maximum number of envelopes you can |
| 19 | +Russian doll is 3 ([2,3] => [5,4] => [6,7]). |
| 20 | +
|
| 21 | +Example 2: |
| 22 | +Input: envelopes = [[1,1],[1,1],[1,1]] |
| 23 | +Output: 1 |
| 24 | +
|
| 25 | +
|
| 26 | +Constraints: |
| 27 | +1 <= envelopes.length <= 5000 |
| 28 | +envelopes[i].length == 2 |
| 29 | +1 <= wi, hi <= 104 |
| 30 | +""" |
| 31 | +from typing import List |
| 32 | +import itertools |
| 33 | +import bisect |
| 34 | + |
| 35 | + |
| 36 | +class Solution: |
| 37 | + def maxEnvelopes(self, envelopes: List[List[int]]) -> int: |
| 38 | + """ |
| 39 | + n = len(envelopes) |
| 40 | + Runtime complexity: O(n log n) |
| 41 | + Space complexity: O(n) |
| 42 | + """ |
| 43 | + widths = list(sorted(set(e[0] for e in envelopes))) |
| 44 | + heights = {h: i for i, h in enumerate(sorted(set(e[1] for e in envelopes)))} |
| 45 | + envelopes_dct = dict() |
| 46 | + for w, h in envelopes: |
| 47 | + if w not in envelopes_dct: |
| 48 | + envelopes_dct[w] = list() |
| 49 | + bisect.insort(envelopes_dct[w], h) |
| 50 | + |
| 51 | + enclosed = [0] * len(heights) |
| 52 | + for w in widths: |
| 53 | + for h in reversed(envelopes_dct[w]): |
| 54 | + i = heights[h] |
| 55 | + if i > 0: |
| 56 | + enclosed[i] = enclosed[i - 1] + 1 |
| 57 | + else: |
| 58 | + enclosed[i] = 1 |
| 59 | + enclosed = list(itertools.accumulate(enclosed, max)) |
| 60 | + return enclosed[-1] |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + import run_tests |
| 65 | + |
| 66 | + correct_answers = [ |
| 67 | + [[[5,4],[6,4],[6,7],[2,3]], 3], |
| 68 | + [[[1,1],[1,1],[1,1]], 1] |
| 69 | + ] |
| 70 | + print(f"Running tests for maxEnvelopes") |
| 71 | + run_tests.run_tests(Solution().maxEnvelopes, correct_answers) |
0 commit comments