Compute the maximal length of the increasing subsequence in an array

The idea to solve this problem goes as follows: Suppose there is an array of n element A. If the maximal length of the increasing sequence lying within the first k elements is known, denoted as L(k), then what we will do next is to compare A[k+1] with the maximal element of that increasing sequence, denoted as M[L(k)]. If A[k+1] is greater than M[L(k)], then the maximal length of the first (k+1) elements is L(k)+1, and M[L(k+1)] is assigned by A[k+1]; If A[k+1] is smaller than M[L(k)], then all the information about the increasing sequence with length L(k) will not be changed, however, A[k+1] may influence the increasing sequence with length L(k)-1, if A[k+1] is greater than its maximal element. If so, M[L(k)] will be updated by A[k] so that there will be more chance for this increasing sequence to grow longer. Therefore, we need to maintain all the maximal elements of increasing sequences with length from 1 to the current maximal length, i.e., the array M. OK, here is the c++ implementation.

  1. #include <iostream>
  2. using namespace std;
  3. // Return the Max Length of Increasing Subsequence (MLIS).
  4. int mlis(int* array, int n) {
  5.     int maxlen = 1;
  6.     int* lis = new int[n]; // lis[i] is the MLIS ending with array[i].
  7.     for(int i = 0; i < n; ++i) {
  8.         lis[i] = 1;
  9.     }
  10.     int* minmax = new int[n+1]; // minmax[i] is the minimal "max value" of subsequence with length i.
  11.     minmax[0] = 0x80000000;
  12.     minmax[1] = array[0];
  13.     for(int i = 1; i < n; ++i) {
  14.         int j;
  15.         for(j = maxlen; j >= 0; --j) {
  16.             if(array[i] > minmax[j]) {
  17.                 lis[i] = j + 1;
  18.                 break;
  19.             }
  20.         }
  21.         if(lis[i] > maxlen) {
  22.             maxlen = lis[i];
  23.             minmax[lis[i]] = array[i];
  24.         }
  25.         else {
  26.             minmax[j+1] = array[i];
  27.         }
  28.     }
  29.     delete[] lis;
  30.     delete[] minmax;
  31.     return maxlen;
  32. }
  33. int main() {
  34.     int array[10] = {3, -2, 2, 1, 5, 6, 3, 4, 8, 7};
  35.     int maxlen = mlis(array, 10);
  36.     cout << "max length: " << maxlen << endl;
  37.     return 0;
  38. }

The command line prints:

max length: 5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值