|
| 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 with a given common difference `diff`. |
| 5 | + int solve(vector<int>& arr, int index, int diff) { |
| 6 | + // Base case: if the index goes out of bounds, return 0 |
| 7 | + if(index < 0) return 0; |
| 8 | + |
| 9 | + int ans = 0; |
| 10 | + // Iterate backwards from the current index to find elements that can form an AP |
| 11 | + for(int j = index - 1; j >= 0; j--) { |
| 12 | + // Check if the difference between arr[index] and arr[j] matches the given `diff` |
| 13 | + if(arr[index] - arr[j] == diff) { |
| 14 | + // Recursively find the length of AP ending at arr[j] and update `ans` |
| 15 | + ans = max(ans, 1 + solve(arr, j, diff)); |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + // Return the maximum length of AP found |
| 20 | + return ans; |
| 21 | + } |
| 22 | + |
| 23 | + // Function to find the length of the longest arithmetic progression in the array |
| 24 | + int lengthOfLongestAP(vector<int>& arr) { |
| 25 | + int n = arr.size(); |
| 26 | + |
| 27 | + // If the array has 2 or fewer elements, the entire array is an AP |
| 28 | + if(n <= 2) return n; |
| 29 | + |
| 30 | + int ans = 0; |
| 31 | + // Iterate through all pairs of elements to calculate the common difference `diff` |
| 32 | + for(int i = 0; i < n; i++) { |
| 33 | + for(int j = i + 1; j < n; j++) { |
| 34 | + // Calculate the common difference and start a recursive search |
| 35 | + // The length of the AP is at least 2 (the current pair) |
| 36 | + ans = max(ans, 2 + solve(arr, i, arr[j] - arr[i])); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // Return the maximum length of the AP found |
| 41 | + return ans; |
| 42 | + } |
| 43 | +}; |
0 commit comments