[LeetCode 354] Russian Doll Envelopes

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)

Note:
Rotation is not allowed.

Example:

Input: [[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]).


Incorrect greedy approach: no matter if we all envelopes by their widths or heights or areas, we can always find counter examples that prove greedy here is incorrect.

 

Solution 1. O(N^2) Dynamic programming

When greedy fails, we can try dynamic programming. First we sort input first by widths then by heights, both in increasing order. Then we define dp[i] to represents the maximum number of envelopes that are used, with the ith envelope being the outmost one. Since we've already sorted the input, to compute dp[i], we just need to check all previous envelopes that can fit inside the ith one and pick the optimal.

 

 

class Solution {
    public int maxEnvelopes(int[][] envelopes) {        
        int n = envelopes.length;
        if(n == 0) return 0;
        Arrays.sort(envelopes, (e1, e2) -> {
            if(e1[0] != e2[0]) {
                return e1[0] - e2[0];
            }  
            return e1[1] - e2[1];
        });
        int[] dp = new int[n];
        int ans = 1;
        Arrays.fill(dp, 1);
        for(int i = 1; i < n; 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);
                }
            }
            ans = Math.max(ans, dp[i]);
        }
        return ans;
    }
}

 

 

 

Solution 2. O(N * logN) LIS

By examing the dp solution, it is clear that this problem is just a variation of the classic LIS problem, the only difference is that here we have 2 metrics width and height to compare with. So we can sort all envelopes by their width and then extract all heights. This way we reduce 2 metrics checking to 1 metric checking, only heights need to be compared at this point since we already guarantee that widths will be in non-decreasing order when processing from left to right. 

 

One corner case is that if we have envelopes of the same width and different height, it is possible that we incorrectly include all of them into the same increasing height sequence. But the width constraint is already violated. To avoid this, when sorting, we first sort by width in ascending order, then sort by heights in descending order. This will make sure that heights of the same width always appear in non-increasing order, thus eliminating the above incorrect corner case situation.

 

 

 

class Solution {
    public int maxEnvelopes(int[][] envelopes) {        
        int n = envelopes.length;
        if(n == 0) return 0;
        Arrays.sort(envelopes, (e1, e2) -> {
            if(e1[0] != e2[0]) {
                return e1[0] - e2[0];
            }  
            return e2[1] - e1[1];
        });
        int[] heights = new int[n];
        for(int i = 0; i < n; i++) {
            heights[i] = envelopes[i][1];
        }
        return lIS(heights);
    }
    private int lIS(int[] a) {
        List<ArrayDeque<Integer>> qlist = new ArrayList<>();
        for(int i = 0; i < a.length; i++) {
            int idx = binarySearch(qlist, a[i]);
            if(idx == qlist.size()) {
                qlist.add(new ArrayDeque<>());
            }
            ArrayDeque<Integer> q = qlist.get(idx);
            q.addFirst(a[i]);
        }    
        return qlist.size();
    }
    private int binarySearch(List<ArrayDeque<Integer>> qlist, int v) {
        if(qlist.size() > 0) {
            int l = 0, r = qlist.size() - 1;
            while(l < r) {
                int mid = l + (r - l) / 2;
                if(qlist.get(mid).peekFirst() < v) {
                    l = mid + 1;
                }
                else {
                    r = mid;
                }
            }
            if(qlist.get(l).peekFirst() >= v) {
                return l;
            }
        }
        return qlist.size();
    }
}

 

 


Related Problems

[LeetCode 300] Longest Increasing Subsequence

posted @ 2021-02-06 03:42  Review->Improve  阅读(33)  评论(0编辑  收藏