|
| 1 | +class Solution { |
| 2 | + public: |
| 3 | + // Helper function to recursively find the length of the longest arithmetic progression (AP) |
| 4 | + // ending at the current index `index` with a given common difference `diff`. |
| 5 | + // The `dp` array is used for memoization to avoid redundant computations. |
| 6 | + int solve(vector<int>& arr, int index, int diff, unordered_map<int, int> dp[]) { |
| 7 | + // Base case: if the index goes out of bounds, return 0 |
| 8 | + if(index < 0) return 0; |
| 9 | + |
| 10 | + // If the result for the current `index` and `diff` is already calculated, return it |
| 11 | + if(dp[index].count(diff)) return dp[index][diff]; |
| 12 | + |
| 13 | + int ans = 0; |
| 14 | + // Iterate backward from the current index to find elements that can extend the AP |
| 15 | + for(int j = index - 1; j >= 0; j--) { |
| 16 | + // Check if the difference between arr[index] and arr[j] matches the given `diff` |
| 17 | + if(arr[index] - arr[j] == diff) { |
| 18 | + // Recursively find the length of the AP ending at arr[j] and update `ans` |
| 19 | + ans = max(ans, 1 + solve(arr, j, diff, dp)); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + // Store the result in the `dp` array and return it |
| 24 | + return dp[index][diff] = ans; |
| 25 | + } |
| 26 | + |
| 27 | + // Function to find the length of the longest arithmetic progression (AP) in the array |
| 28 | + int lengthOfLongestAP(vector<int>& arr) { |
| 29 | + int n = arr.size(); |
| 30 | + |
| 31 | + // If the array has 2 or fewer elements, the entire array is an AP |
| 32 | + if(n <= 2) return n; |
| 33 | + |
| 34 | + // `dp[i]` is an unordered map where the key is the difference `diff` and the value |
| 35 | + // is the length of the longest AP ending at index `i` with that difference |
| 36 | + unordered_map<int, int> dp[n + 1]; |
| 37 | + |
| 38 | + int ans = 0; // Variable to store the maximum length of AP found |
| 39 | + // Iterate through all pairs of elements to calculate the common difference `diff` |
| 40 | + for(int i = 0; i < n; i++) { |
| 41 | + for(int j = i + 1; j < n; j++) { |
| 42 | + // Calculate the common difference and start a recursive search |
| 43 | + // The length of the AP is at least 2 (the current pair) |
| 44 | + ans = max(ans, 2 + solve(arr, i, arr[j] - arr[i], dp)); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // Return the maximum length of AP found |
| 49 | + return ans; |
| 50 | + } |
| 51 | +}; |
0 commit comments