# 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)

This problem is similar to Longeset Increasing Subsequence.

Java Solution 1 - Naive

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

Java Solution 2 - Binary Search

```public int maxEnvelopes(int[][] envelopes) { if(envelopes==null||envelopes.length==0) return 0;   Arrays.sort(envelopes, new Comparator<int[]>(){ public int compare(int[] a, int[] b){ if(a[0]!=b[0]){ return a[0]-b[0]; //ascending order }else{ return b[1]-a[1]; // descending order } } });   ArrayList<Integer> list = new ArrayList<Integer>();   for(int i=0; i<envelopes.length; i++){   if(list.size()==0 || list.get(list.size()-1)<envelopes[i][1]) list.add(envelopes[i][1]);   int l=0; int r=list.size()-1;   while(l<r){ int m=l+(r-l)/2; if(list.get(m)<envelopes[i][1]){ l=m+1; }else{ r=m; } }   list.set(r, envelopes[i][1]); }   return list.size(); }```
Category >> Algorithms
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
1. Feeey on 2017-1-9

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

2. 杜永道 on 2017-10-24

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.
https://www.helplib.com/