#codingexercise
Get the widest difference between two indexes in an array of random integers such that the integer at the second index is greater than that of the first.
import java.util.Arrays;
public class LongestIncreasingSubsequence {
public static void main(String[] args) {
int[] arr = {10, 22, 9, 33, 21, 50, 41, 60, 80};
System.out.println(GetWidestDifferenceBetweenIndicesOfLIS(arr));
}
public static int GetWidestDifferenceBetweenIndicesofLIS(int[] arr) {
int n = arr.length;
int[] lis = new int[n+1];
for (int i = 0; i < n+1; i++) {
lis[i] = 1; // Initialize LIS value for each element
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (arr[i] > arr[j]) {
lis[i] = Math.max(lis[i], lis[j] + 1);
}
}
}
// lis = 1,2,1,3,2,4,4,5,6
int max_length = Arrays.stream(lis).max().orElse(0);
if (max_length == 0) return 0;
if (max_length == 1) return 1;
int last = -1;
for (int i = n-1; i >= 0; i++) {
if (lis[I] == max_length ) {
last = i;
}
}
int first = 0;
for (int i = 0; i < n; i++) {
if (lis[i] == 2) {
first = i;
break;
}
}
for(int I = 0; I < first; i++) {
if (arr[i] < arr[first]) {
first = I;
break;
}
}
Return last-first+1;
}
}
9
#booksummary: BookSummary233.docx
No comments:
Post a Comment