13. Russian Doll Envelopes

Link to the problem

Description

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)

Example

Input: [[5,4],[6,4],[6,7],[2,3]], Output: 3

Idea

Sort the dolls by width, then by opposite of height. Find the longest increasing subsequence of the height.

Solution

class Solution {
private:
    int lis(vector<int> &nums) {
        int n = nums.size();
        if (!n) return 0;
        int maxSoFar = 0;
        vector<int> tail(n); // dp[i] stores the tail for increasing subsequence of length i + 1
        int lis = 0;
        for (int i = 0; i < n; i++) {
            auto replace = lower_bound(tail.begin(), tail.begin() + lis, nums[i]);
            *replace = nums[i];
            if (replace == tail.begin() + lis) lis++;
        }
        return lis;
    }
public:
    int maxEnvelopes(vector<pair<int, int> >& envelopes) {
        sort(envelopes.begin(), envelopes.end(),
            [] (const auto &lhs, const auto &rhs) {
               return lhs.first < rhs.first || (lhs.first == rhs.first && lhs.second > rhs.second); 
            });
        vector<int> nums;
        for (auto it = envelopes.begin(); it != envelopes.end(); it++) {
            nums.push_back(it->second);
        }
        return lis(nums);
    }
};

85 / 85 test cases passed.
Runtime: 26 ms

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,516评论 0 23
  • 随着现代信息技术与课堂教学的整合,多媒体普遍走进课堂。在运用多媒体教学中,课件以其信息量大、感染力强、易操作等优点...
    雪花杨絮阅读 4,516评论 2 5
  • 一 三山五岳,只去了一座泰山,还一去再去。非为喜欢,只因方便,也为着身边的人。 计划中本要去黄山,但因为家中长辈的...
    柳桥阅读 3,177评论 0 1
  • 军改已毕。许多没有退伍、转业的军人留在了部队,继续保家卫国。但接下来他们应对的又将是工作调动的问题。对于他们来说,...
    月华军之恋阅读 4,483评论 0 5
  • 一曲狂歌几十年, 多少白发旧容颜。 寥寥不过当日怨, 相逢笑谈旧云天!
    烽梓阅读 1,657评论 0 0

友情链接更多精彩内容