Sponsored
Sponsored
This approach uses a hash map (or dictionary) to keep track of the longest subsequence length that can be achieved ending with a specific value. For each element in the array, we check if there is an arithmetic subsequence ending with the element minus the given difference. If such a subsequence exists, we calculate the current subsequence length. Otherwise, we start a new subsequence from this element.
Time Complexity: O(n), where n is the length of arr. We iterate over the array once.
Space Complexity: O(n), where n is the number of distinct elements in arr stored in the dictionary.
1import java.util.HashMap;
2
3public class Solution {
4 public int longestSubsequence(int[] arr, int difference) {
5 HashMap<Integer, Integer> dp = new HashMap<>();
6 int max_length = 0;
7 for (int num : arr) {
8 dp.put(num, dp.getOrDefault(num - difference, 0) + 1);
9 max_length = Math.max(max_length, dp.get(num));
10 }
11 return max_length;
12 }
13}
In this Java solution, a HashMap is used in a similar way as in other languages to track subsequence lengths. We update our map at every step to maintain the potential subsequence count for each number.
This approach utilizes an array to store information about each possible element value scaled according to the constraints. For each element in arr, determine if there is a previous subsequence that can be extended using direct array access.
Time Complexity: O(n), where n is the length of arr.
Space Complexity: O(1) (constant size array mentioned in constraints).
The C solution uses predefined arrays and simple indexing to avoid dynamic memory allocations and achieve time-efficient computations over elements in arr.