|
| 1 | +package com.thealgorithms.dynamicprogramming; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | + |
| 5 | +final class LongestArithmeticSubsequence { |
| 6 | + |
| 7 | + private LongestArithmeticSubsequence() { |
| 8 | + } |
| 9 | + |
| 10 | + /** |
| 11 | + * Returns the length of the longest arithmetic subsequence in the given array. |
| 12 | + * |
| 13 | + * A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value |
| 14 | + * (for 0 <= i < seq.length - 1). |
| 15 | + * |
| 16 | + * @param nums the input array of integers |
| 17 | + * @return the length of the longest arithmetic subsequence |
| 18 | + */ |
| 19 | + public static int getLongestArithmeticSubsequenceLength(int[] nums) { |
| 20 | + // If the array is empty or has only one element, return its length. |
| 21 | + if (nums == null || nums.length == 0) { |
| 22 | + return 0; |
| 23 | + } |
| 24 | + |
| 25 | + if (nums.length == 1) { |
| 26 | + return 1; |
| 27 | + } |
| 28 | + |
| 29 | + int n = nums.length; |
| 30 | + HashMap<Integer, Integer>[] dp = new HashMap[n]; |
| 31 | + int maxLength = 2; |
| 32 | + |
| 33 | + // Initialize dp array |
| 34 | + for (int i = 0; i < n; i++) { |
| 35 | + dp[i] = new HashMap<>(); |
| 36 | + for (int j = 0; j < i; j++) { |
| 37 | + int diff = nums[i] - nums[j]; |
| 38 | + dp[i].put(diff, dp[j].getOrDefault(diff, 1) + 1); |
| 39 | + maxLength = Math.max(maxLength, dp[i].get(diff)); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return maxLength; |
| 44 | + } |
| 45 | + |
| 46 | + public static void main(String[] args) { |
| 47 | + int[] nums = {3, 6, 9, 12, 15}; |
| 48 | + int length = getLongestArithmeticSubsequenceLength(nums); |
| 49 | + |
| 50 | + // Print the result |
| 51 | + System.out.println("Array: "); |
| 52 | + for (int num : nums) { |
| 53 | + System.out.print(num + " "); |
| 54 | + } |
| 55 | + System.out.println(); |
| 56 | + System.out.println("Length of the Longest Arithmetic Subsequence: " + length); |
| 57 | + } |
| 58 | +} |
0 commit comments