File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
24 - Dynamic Programming Problems/26 - Longest Arithmetic Subsequence Expand file tree Collapse file tree 1 file changed +37
-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 progression (AP) in the array
4+ int lengthOfLongestAP (vector<int >& arr) {
5+ int n = arr.size ();
6+
7+ // If the array has 2 or fewer elements, the entire array is an AP
8+ if (n <= 2 ) return n;
9+
10+ int ans = 0 ; // Variable to store the maximum length of AP found
11+
12+ // `dp[i]` is an unordered map where the key is the difference `diff`
13+ // and the value is the length of the longest AP ending at index `i` with that difference
14+ unordered_map<int , int > dp[n + 1 ];
15+
16+ // Iterate through all pairs of elements to build the `dp` table
17+ for (int i = 1 ; i < n; i++) { // Start from the second element
18+ for (int j = 0 ; j < i; j++) { // Compare with all previous elements
19+ // Calculate the common difference between arr[i] and arr[j]
20+ int diff = arr[i] - arr[j];
21+ int count = 1 ; // Minimum length of AP (current pair)
22+
23+ // If there exists an AP ending at `j` with the same `diff`, retrieve its length
24+ if (dp[j].count (diff)) count = dp[j][diff];
25+
26+ // Extend the AP by including the current element at `i`
27+ dp[i][diff] = 1 + count;
28+
29+ // Update the maximum length of AP found so far
30+ ans = max (ans, dp[i][diff]);
31+ }
32+ }
33+
34+ // Return the maximum length of AP
35+ return ans;
36+ }
37+ };
You can’t perform that action at this time.
0 commit comments