|
| 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 = 2; // Minimum length of an AP is 2 |
| 11 | + |
| 12 | + // `dp` is a 2D map where: |
| 13 | + // - The first key represents the index `i` of the array |
| 14 | + // - The second key represents the difference `diff` |
| 15 | + // - The value is the length of the longest AP ending at `i` with common difference `diff` |
| 16 | + unordered_map<int, unordered_map<int, int>> dp; |
| 17 | + |
| 18 | + // Iterate through all pairs of elements to fill the `dp` map |
| 19 | + for(int i = 1; i < n; i++) { // Start from the second element |
| 20 | + for(int j = 0; j < i; j++) { // Compare with all previous elements |
| 21 | + // Calculate the common difference between `arr[i]` and `arr[j]` |
| 22 | + int diff = arr[i] - arr[j]; |
| 23 | + |
| 24 | + // Retrieve the length of the AP ending at `j` with the same `diff` |
| 25 | + // If no such AP exists, initialize it with length 1 (current pair) |
| 26 | + int count = dp[j][diff] ? dp[j][diff] : 1; |
| 27 | + |
| 28 | + // Update the length of the AP ending at `i` with the same `diff` |
| 29 | + dp[i][diff] = count + 1; |
| 30 | + |
| 31 | + // Update the maximum length of AP found so far |
| 32 | + ans = max(ans, dp[i][diff]); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + // Return the maximum length of AP found |
| 37 | + return ans; |
| 38 | + } |
| 39 | +}; |
0 commit comments