don’t even need to sort by sum actually. we just need to sort by width. at first sorting by width is natural, but then we run into the problem of what if two envelopes have the sum width but differing heights (which would be in ascending as well since the width causes a tiebreaker). we don’t want to count envelopes[j] (if j < i) just because envelopes[i] > envelopes[i] – we need both width and height to be larger – so let’s just do an extra check to make sure the width is larger too! thus, technically its
if envelopes[i] > envelopes[j] and envelopes[i] > envelopes[j] though you could rewrite it width the width check first for it to look better, but the logic is that we are looking for a LIS in the height after the initial sort, and then need to do an extra check for the width not matching!
This solution will time out!
Can you elaborate?
You can sort by both width and height:
sorted(envelopes, key=lambda x: (x, x))
Solution times out on leetcode… at least when i checked
def binarysearch(arr, target):
l = 0
r = len(arr) - 1
bi = -1
while l <= r: m = (l+r)//2 mid = arr[m] if mid == target: bi = m break elif mid > target: bi = m r = m - 1 elif mid < target: l = m + 1 arr[bi] = target
def max_layers(envelopes: List[List[int]]) → int:
envelopes.sort(key=lambda x: (x,-x)) dp =  for e in envelopes: if not dp: dp.append(e) continue last = dp[-1] if last < e: dp.append(e) else: binarysearch(dp, e) return len(dp)
That’s the default behavior, you don’t need the lambda.
Mods should include the binary search solution to solve this problem which is detailed here: