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.
1#include <vector>
2#include <unordered_map>
3using namespace std;
4
5int longestSubsequence(vector<int>& arr, int difference) {
6 unordered_map<int, int> dp;
7 int max_length = 0;
8 for (int num : arr) {
9 dp[num] = dp[num - difference] + 1;
10 max_length = max(max_length, dp[num]);
11 }
12 return max_length;
13}
This C++ solution uses an unordered_map to store the longest subsequence lengths. For each number in the array, we check the length of the subsequence ending with the previous number minus the difference.
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).
This Java implementation constructs an approach using an array, invoking fewer method calls by direct access via indexed offsets for subsequence calculations.