Tuesday, February 27, 2024

 

Get the Longest Increasing Subsequence:

For example, the LIS of [10, 9, 2, 5, 3, 7, 101, 18] is [2, 5, 7, 101] and its size() is 4.

public static int getLIS(List<Integer> A) {

if (A == null || A.size() == 0) return 0;

var best = new int[A.size() + 1];

for (int I = 0; I < A.size(); i++)

      best[i] = 1;

for (int I = 1; I < A.size(); i++)

 {

     for (int j = 0; j < I; j++) {

            if (A[i] > A[j]) {

                   best[i]  = Math.Max(best[i], best[j] + 1);

            }

     }

}

List<Integer> b = Arrays.asList(ArrayUtils.toObject(best));

return b.stream()

.max(Comparator.comparing(Integer::valueOf))

.get();

}

 

Generate the Nth Fibonacci number.

Fibonacci series is like this: 1, 1, 2, 3, 5, 8, 13, …

int GetFib(int n) {

if (n <= 0) return 0;

if (n == 1) return 1;

if (n == 2) return 1;

return GetFib(n-1) + GetFib(n-2);

}

 

No comments:

Post a Comment