-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquaresOfASortedArray.cpp
More file actions
37 lines (36 loc) · 891 Bytes
/
SquaresOfASortedArray.cpp
File metadata and controls
37 lines (36 loc) · 891 Bytes
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
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[]={-4,-1,0,3,7,10};
int n=sizeof(a)/sizeof(a[0]);
//Two pointer approach is used
//make a result array and store the values in it from n-1 position
//laregst number is choosed and put into the result array
int l=0; //two pointers left and right
int r=n-1;
int res[n]; //result array
//now lets comapre the squared values and store the largest one in the result array
int index=n-1;
while(l<=r) //loop will run till left pointer is less than equal to right pointer
{
int val1=a[l]*a[l];
int val2=a[r]*a[r];
if(val1>val2)
{
res[index]=val1;
l++;
}
else
{
res[index]=val2;
r--;
}
index--;
}
for(int i=0;i<n;i++)
{
cout<<res[i]<<" ";
}
return 0;
}