Skip to content

Commit 805d2c2

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 1c76cd6 commit 805d2c2

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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

Comments
 (0)