Responsive Ads Here

Tuesday 25 July 2017

Check Arithmetic Progression

In this question you can use Hashing or priority_queue.
I have used Priority queue(Heap )
First of all push all elements in the heap .I elements is less than or
equal to 2. then AP can be formed . Else go for the approach (I mean)
find the common diff and check through out the array to find that they have
same common diff.That it. :)

problem id:-http://practice.geeksforgeeks.org/problems/check-arithmetic-progression/0
code:-

#include <bits/stdc++.h>

using namespace std;

#define sc(x)   scanf("%d",&x)
#define      rep(i, n)         for(int i = 0; i < (n); ++i)


int main(int argc, char **argv) {
priority_queue<int> pq;
string ans[]={"YES\n","NO\n"};
int t;
sc(t);
while(t--)
{
int n;
sc(n);
int num;
rep(i,n) {sc(num); pq.push(num); }
if(pq.size()<=2)
{
cout<<ans[0];
continue;
}
int num1,num2,diff,temp_diff;
num1=pq.top();
pq.pop();
num2=pq.top();
pq.pop();
diff=num2-num1;
bool flag=0;
while(!pq.empty())
{
num1=num2;
num2=pq.top();
pq.pop();
temp_diff=num2-num1;
if(temp_diff!=diff)
{
flag=1;
break;
}
}
cout<<ans[flag];
}
return 0;
}

No comments:

Post a Comment