Search

Russian Doll Envelopes

You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.


One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.


Return the maximum number of envelopes can you Russian doll (i.e., put one inside the other).

Note: You cannot rotate an envelope.


Example 1:

Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

Example 2:

Input: envelopes = [[1,1],[1,1],[1,1]]
Output: 1

Constraints:

  • 1 <= envelopes.length <= 5000

  • envelopes[i].length == 2

  • 1 <= wi, hi <= 104

Solution:


Approach 1: Dp


class Solution {
public int maxEnvelopes(int[][] envelopes) {
        Arrays.sort(envelopes,(a,b)-> a[0]==b[0]?a[1]-b[1]:a[0]-b[0]);
        int result=1;
        int[] dp = new int[envelopes.length];
        Arrays.fill(dp,1);
        for(int i=1;i<envelopes.length;i++)
        {
            for(int j=0;j<i;j++)
            {
                if(envelopes[i][0]>envelopes[j][0] && envelopes[i][1]>envelopes[j][1])
                {
                    dp[i]=Math.max(dp[i],dp[j]+1);
                }
                result=Math.max(result,dp[i]);
            }
        }
        return result;
    }
}


Approach 2: Patience sort (Longest Increasing Subsequence)


class Solution {
   public int maxEnvelopes(int[][] envelopes) {
        Arrays.sort(envelopes,(a,b)->a[0]==b[0]?b[1]-a[1]:a[0]-b[0]);
        TreeSet<Integer> set = new TreeSet<>();
        for(int[] envelope: envelopes) 
        {
            Integer height = set.ceiling(envelope[1]);        
            if (height != null) 
            {
                set.remove(height);
            }
            set.add(envelope[1]);
        }
        return set.size();
    }
}
21 views0 comments

Recent Posts

See All

A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The f

The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.