File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
24 - Dynamic Programming Problems/27 - Longest Arithmetic Subsequence of Given Difference Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Function to find the length of the longest arithmetic subsequence with the given difference
4+ int longestSubsequence (vector<int >& arr, int difference) {
5+ int n = arr.size (); // Get the size of the input array
6+ unordered_map<int , int > dp; // Map to store the longest subsequence length for each element
7+
8+ int ans = 0 ; // Variable to store the maximum length of any subsequence found so far
9+
10+ // Iterate through each element of the array
11+ for (int i = 0 ; i < n; i++) {
12+ // Calculate the previous element in the subsequence with the given difference
13+ int temp = arr[i] - difference;
14+
15+ // If there's a subsequence ending with `temp`, we get its length from dp. If not, set prevAns to 0
16+ int prevAns = dp.count (temp) ? dp[temp] : 0 ;
17+
18+ // Update the longest subsequence ending at arr[i], adding 1 to the length of the previous subsequence
19+ dp[arr[i]] = 1 + prevAns;
20+
21+ // Update the maximum subsequence length found so far
22+ ans = max (ans, dp[arr[i]]);
23+ }
24+
25+ // Return the maximum length of the subsequence found
26+ return ans;
27+ }
28+ };
You can’t perform that action at this time.
0 commit comments