LeetCode – Russian Doll Envelopes (Java)

You have a number of envelopes with widths and heights given as a pair of integers (w, h). 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.

What is the maximum number of envelopes can you Russian doll? (put one inside other)

Java Solution 1 - Naive

public int maxEnvelopes(int[][] envelopes) {
        return 0;
    Arrays.sort(envelopes, new Comparator<int[]>(){
        public int compare(int[] a, int[] b){
                return a[0]-b[0];
                return a[1]-b[1];
    int max=1;
    int[] arr = new int[envelopes.length];
    for(int i=0; i<envelopes.length; i++){
        for(int j=i-1; j>=0; j--){
                arr[i]=Math.max(arr[i], arr[j]+1);
        max = Math.max(max, arr[i]);
    return max;

Java Solution 2 - Binary Search

We can sort the envelopes by height in ascending order and width in descending order. Then look at the width and find the longest increasing subsequence. This problem is then converted to the problem of finding Longeset Increasing Subsequence.

public int maxEnvelopes(int[][] envelopes) {
    Comparator c = Comparator.comparing((int[] arr) -> arr[0])
                                .thenComparing((int[] arr) -> arr[1], Comparator.reverseOrder());
    Arrays.sort(envelopes, c);
    ArrayList<Integer> list = new ArrayList<>();
    for(int[] arr: envelopes){
        int target = arr[1];
            int i=0; 
            int j=list.size()-1;
                int m = i + (j-i)/2;
                    j = m;
                    i = m+1;
            list.set(j, target);
    return list.size();

Time complexity is O(n*log(n)) and we need O(n) of space for the list.

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Greenglade

    bury her

  • alexwest11

    other version of stacking boxes..???

    obv must be dp solution

  • Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

  • 嗨~我是Feeey 不小心进了你的博客,很棒。记得来我博客转转 http://www.feeey.com/