-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathLongest Arithmetic Subarray.cpp
More file actions
59 lines (48 loc) · 1.08 KB
/
Longest Arithmetic Subarray.cpp
File metadata and controls
59 lines (48 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <bits/stdc++.h>
using namespace std;
// Function to return the length
// of longest subarray forming an AP
int getMaxLength(int arr[], int N)
{
// Minimum possible length of
// required subarray is 2
int res = 2;
// Stores the length of the
// current subarray
int dist = 2;
// Stores the common difference
// of the current AP
int curradj = (arr[1] - arr[0]);
// Stores the common difference
// of the previous AP
int prevadj = (arr[1] - arr[0]);
for (int i = 2; i < N; i++) {
curradj = arr[i] - arr[i - 1];
// If the common differences
// are found to be equal
if (curradj == prevadj) {
// Continue the previous subarray
dist++;
}
// Start a new subarray
else {
prevadj = curradj;
// Update the length to
// store maximum length
res = max(res, dist);
dist = 2;
}
}
// Update the length to
// store maximum length
res = max(res, dist);
// Return the length of
// the longest subarray
return res;
}
int main()
{
int arr[] = { 10, 7, 4, 6, 8, 10, 11 };
int N = sizeof(arr) / sizeof(arr[0]);
cout << getMaxLength(arr, N);
}