Russian Doll Envelopes in C++

Suppose we have some envelops, these envelops has height and width values as pairs. We can put one envelop into another one if the height and width of second envelop both are smaller than the height and width of the first one. So, what will be the maximum number of envelops that we can put inside other. So, if the inputs are like [[5,5], [6,4], [6,8], [2,3]], then the output will be 3, as smallest envelop is [2,3], then [5,5], then [6,8].

To solve this, we will follow these steps −

  • sort the array v based on height, when heights are same, compare with width
  • if size of v is same as 0, then −
    • return 0
  • Define an array ret
  • for initialize i := 0, when i
  • Define an array temp = v[i]
  • x := temp[1]
  • low := 0, high := size of ret, curr := 0
  • while low
  • mid := low + (high - low) / 2
  • if ret[mid]
  • curr := mid + 1
  • low := mid + 1
  • Otherwise
    • high := mid - 1
  • if curr
  • Ignore following part, skip to the next iteration
  • if curr >= size of ret, then −
    • insert temp[1] at the end of ret
  • Otherwise
    • ret[curr] := temp[1]
  • return size of ret
  • Let us see the following implementation to get better understanding −

    Example

     Live Demo

    #include 
    using namespace std;
    class Solution {
    public:
       static bool cmp(vector  a, vector  b){
          if(a[0] == b[0])return a[1] > b[1];
          return a[0] >& v) {
          sort(v.begin(), v.end(), cmp);
          if(v.size() == 0)return 0;
          vector  ret;
          for(int i = 0; i  temp = v[i];
             int x = temp[1];
             int low = 0;
             int high = ret.size() -1;
             int curr = 0;
             while(low = (int)ret.size()){
                ret.push_back(temp[1]);;
             }else{
                ret[curr] = temp[1];
             }
          }
          return ret.size();
       }
    };
    main(){
       Solution ob;
       vector> v = {{5,5}, {6,4}, {6,8}, {2,3}};
       cout 

    Input

    {{5,5}, {6,4}, {6,8}, {2,3}}

    Output

    3
    Updated on: 2020-06-01T10:40:55+05:30

    587 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements