How to determine the longest increasing subsequence using dynamic programming?

前端 未结 19 2739
醉梦人生
醉梦人生 2020-11-22 10:55

I have a set of integers. I want to find the longest increasing subsequence of that set using dynamic programming.

19条回答
  •  误落风尘
    2020-11-22 11:16

    The O(NLog(N)) Approach To Find Longest Increasing Sub sequence
    Let us maintain an array where the ith element is the smallest possible number with which a i sized sub sequence can end.

    On purpose I am avoiding further details as the top voted answer already explains it, but this technique eventually leads to a neat implementation using the set data structure (at least in c++).

    Here is the implementation in c++ (assuming strictly increasing longest sub sequence size is required)

    #include  // gcc supported header to include (almost) everything
    using namespace std;
    typedef long long ll;
    
    int main()
    {
      ll n;
      cin >> n;
      ll arr[n];
      set S;
    
      for(ll i=0; i> arr[i];
        auto it = S.lower_bound(arr[i]);
        if(it != S.end())
          S.erase(it);
        S.insert(arr[i]);
      }
    
      cout << S.size() << endl; // Size of the set is the required answer
    
      return 0;
    }
    

提交回复
热议问题