Skip to content

Create Longest Arithmetic Subarray.cpp #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions HacktoberFest2021/C++ Programs/Longest Arithmetic Subarray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,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);
}