Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 354 Russian Doll Envelopes - Walkthrough

2D LIS reduction

Envelopes are (w,h)(w, h) pairs. You can nest envelope aa inside bb if a.w<b.wa.w < b.w and a.h<b.ha.h < b.h. Sort by width ascending, then by height descending within same width. This keeps we can't nest envelopes with same width.

Now run LIS on the heights. The descending tie-break prevents using two envelopes with same width. Example: [(5,4),(6,4),(6,7),(2,3)][(5,4), (6,4), (6,7), (2,3)] → sorted: [(2,3),(5,4),(6,7),(6,4)][(2,3), (5,4), (6,7), (6,4)] → heights: [3,4,7,4][3, 4, 7, 4] → LIS: 33.