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).
public class Solution {
public int LongestSubsequence(int[] arr, int difference) {
int[] dp = new int[20001];
int offset = 10000;
int max_length = 0;
foreach (int num in arr) {
int idx = num + offset;
int prev_idx = num - difference + offset;
dp[idx] = dp[prev_idx] + 1;
max_length = Math.Max(max_length, dp[idx]);
}
return max_length;
}
}
This C# solution aligns indices to fixed array positions using calculated offsets to enhance direct value access, resulting in rapid sequence length calculations without extra storage overhead.