简体   繁体   中英

Find the length of longest increasing subsequence C++

Please help me solve this problem, when input 10 and 1 2 3 1 2 3 3 4 5 6

Output should be 4 but it's 6 .

In all other tests, the program is working well.

For Example:

Input: 1   -10
Output: 1

Input: 2   123 123
Output: 1

Input: 2   -1245 234
Output: 2

Input: 5   1 2 3 -1 -20
Output: 3

Input: 5   1 1 2 3 1
Output: 3

Input: 5   0 0 0 1 10000
Output: 3

Thanks in advance!

#include <iostream>
using namespace std;

int subsequence(int arr[], int n) {

 int* length = new int[n];
 int max_length = 0;

 for (int i = 0; i < n; i++) {  
    for (int j = 0; j < i; j++) { 
       if (arr[j] < arr[i] && length[j] > length[i])
          length[i] = length[j];
    }
        length[i]++; 
 }
 for (int i = 0; i < n; i++) { 
    max_length = max(max_length, length[i]);
 }
 delete [] length;

      return max_length;
}
int main() {
  int n;
      cin >> n;
  int* arr = new int[n];
  for(int i = 0; i < n; ++i) {
      cin >> arr[i];
  }
      cout << subsequence(arr, n);

      return 0;
}

Firstly, the length array values are unitialized, this will invoke undefined behavior, in your case, by chance, it works, but you should expect that whatever garbage values are in the array will be used as a comparison, to avoid this you should fill it with 0 s.

Then, this piece of code:

for (int i = 0; i < n; i++)
{
    max_length = max(max_length, length[i]);   
    std::cout << max_length << " ";    
}

This means, broadly speaking, that the max_length will increase as long as the next number is larger than the previous, there is no variable reset, both sequences are counted:

1 2 3 1 2 3 3 4 5 6  //input sequence

1 2 3 3 3 3 3 4 5 6  //max_length value along the function
^ ^ ^         ^ ^ ^
+ + +         + + +

Hence the 6 output.

That said, you wouldn't need such a convoluted piece of code for such a simple task, if you just need to count the max sequence, something along the lines of:

int subsequence(int arr[], int n) {

    int max_length = 1; //hold the max_length
    int temp = 1;       //hold the temporary max_length

    for (int i = 0; i < n - 1; i++) {
        if(arr[i + 1] > arr[i]) { 
            temp++;     //if the next value is larger increase temp
            max_length = std::max(max_length, temp); //assign largest temp to max_length
        }
        else{     
            temp = 1;   //otherwise reset temp
        }    
    }
    return max_length;  //return max_length
}

Side note:

Since you're using C++, you could upgrade your code to use C++ containers instead of C style arrays, std::vector in this case, given the variable size array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM