← Back to index
HardPHP4 min read

Russian Doll Envelopes

find maximum number of envelopes that can be nested using longest increasing subsequence on sorted envelopes.

dynamic-programmingbinary-searchsorting

Problem link

View on LeetCode

Solutions in this repo

  • PHP../russian-doll-envelopes/solution.phpPHP solution

sort envelopes by width ascending, then by height descending (to avoid same-width nesting). then find longest increasing subsequence (LIS) on heights.

use binary search LIS: maintain array of smallest tail values for each length. for each envelope, find position to extend or start new sequence.

key insight

sorting by width then height (descending) converts 2d problem to 1d LIS problem. binary search LIS gives O(n log n) solution.

complexity

O(n log n) time for sorting and LIS. O(n) space for LIS array. efficient solution.