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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,052評論 0 23
  • 隨著現(xiàn)代信息技術(shù)與課堂教學(xué)的整合,多媒體普遍走進課堂。在運用多媒體教學(xué)中,課件以其信息量大、感染力強、易操作等優(yōu)點...
    雪花楊絮閱讀 1,016評論 2 5
  • 一 三山五岳,只去了一座泰山,還一去再去。非為喜歡,只因方便,也為著身邊的人。 計劃中本要去黃山,但因為家中長輩的...
    柳橋閱讀 471評論 0 1
  • 軍改已畢。許多沒有退伍、轉(zhuǎn)業(yè)的軍人留在了部隊,繼續(xù)保家衛(wèi)國。但接下來他們應(yīng)對的又將是工作調(diào)動的問題。對于他們來說,...
    月華軍之戀閱讀 997評論 0 5
  • 一曲狂歌幾十年, 多少白發(fā)舊容顏。 寥寥不過當(dāng)日怨, 相逢笑談舊云天!
    烽梓閱讀 255評論 0 0

友情鏈接更多精彩內(nèi)容