#include <stdio.h> void findLongestSubsequence(int a[], int n) { int lengths[n]; int…
- User
#include <stdio.h>
void findLongestSubsequence(int a[], int n) { int lengths[n]; int prevIndices[n]; int maxLength = 1; int endIndex = 0;
code// Initialize lengths and prevIndices arrays for (int i = 0; i < n; i++) { lengths[i] = 1; prevIndices[i] = -1; } // Find lengths of increasing subsequences for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (a[i] > a[j] && lengths[j] + 1 > lengths[i]) { lengths[i] = lengths[j] + 1; prevIndices[i] = j; if (lengths[i] > maxLength) { maxLength = lengths[i]; endIndex = i; } } } } // Print the length of the longest increasing subsequence printf("%d\n", maxLength); // Print the indices of the elements in the longest increasing subsequence int indices[maxLength]; int current = endIndex; while (current >= 0) { indices[--maxLength] = current; current = prevIndices[current]; } for (int i = 0; i < maxLength; i++) { printf("%d ", indices[i]); } printf("\n");}
int main() { int n; scanf("%d", &n); int a[n];
codefor (int i = 0; i < n; i++) { scanf("%d", &a[i]); } findLongestSubsequence(a, n); return 0;}
for input- 9 1 5 6 7 2 8 3 4 10 output should be - 4 0 4 6 7
- Assistant
The code provided does a good job of computing the longest increasing subsequence (LIS) in an array and its length. However, there seems to be a small mistake in the printing section of the function, which can lead to printing incorrect indices or not printing any indices at all. Specifically, the mistake is in the loop where the indices are meant to be printed. It uses the variable, which is being decremented inside the while loop and is not reset to its original value before printing.
- User
#include <stdio.h>
// struct node // { // int data; // int index; // struct node *next; // };
int main() { int n; scanf("%d", &n); int arr[n]; int freq[n];
code// struct node *head = NULL; // struct node *temp = head; for (int i = 0; i < n; i++) { int data; scanf("%d", &arr[i]); freq[(arr[i]%n)]=i; //printf("arr[i]-%d\t freq[i]-%d\t i-%d\n",arr[i],freq[i],i); } int max=0; int length=1; int start=0; int ini=0;for (int i = 0; i < n; i++) { int currentLength = 1; int currentIndex = i;
codewhile (freq[arr[currentIndex] + 1] > freq[arr[currentIndex]] && (arr[currentIndex] + 1) <= n) { currentLength++; currentIndex++; } if (currentLength > max) { max = currentLength; ini = i; } } printf("%d\n", max); for (int j = ini; j < ini + max; j++) { printf("%d ", freq[arr[j]]); } // qsort((void*)arr, size, sizeof(arr[0]), comparator); return 0; - Assistant