Finding the longest decreasing subsequence.
Below is a Java program that finds the longest decreasing subsequence of an array:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class LongestDecreasingSubsequence { public static List<Integer> findLongestDecreasingSubsequence(int[] nums) { int n = nums.length; int[] dp = new int[n]; Arrays.fill(dp, 1); for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (nums[i] < nums[j] && dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1; } } } int maxLength = dp[0]; int maxIndex = 0; for (int i = 1; i < n; i++) { if (dp[i] > maxLength) { maxLength = dp[i]; maxIndex = i; } } List<Integer> subsequence = new ArrayList<>(); int length = maxLength; subsequence.add(nums[maxIndex]); for (int i = maxIndex - 1; i >= 0; i--) { if (nums[i] > nums[maxIndex] && dp[i] == length - 1) { subsequence.add(nums[i]); length--; maxIndex = i; } } return subsequence; } public static void main(String[] args) { int[] nums = {5, 2, 8, 6, 3, 6, 9, 7}; List<Integer> longestDecreasingSubsequence = findLongestDecreasingSubsequence(nums); System.out.println("Longest Decreasing Subsequence: " + longestDecreasingSubsequence); } }
In this program, the `findLongestDecreasingSubsequence` method takes an array of integers as input and returns the longest decreasing subsequence as a list of integers. The program uses dynamic programming to solve the problem.
In the `main` method, we create an example array `nums` and call the `findLongestDecreasingSubsequence` method to find the longest decreasing subsequence. Finally, we print the result.
The output for the provided example array would be:
Longest Decreasing Subsequence: [8, 6, 3]
This means that the longest decreasing subsequence in the array `[5, 2, 8, 6, 3, 6, 9, 7]` is `[8, 6, 3]`.
No comments yet! You be the first to comment.