Achieve a task using a single loop instead of 2 c++`
This is a task specific code for which I want to know if there's a better
way of doing it. Thus, people who love logic and coding, please help me
out.
This is the question :
Let A be an array of n positive integers. All the elements are distinct.
If A[i] > A[j] and i < j then the pair (i, j) is called a special pair of
A. Given n find the number of special pairs of A.
Its pretty simple and straight. Here's the following solution I
implemented. The logic part.
for(int j=0;j<nos.size();j++)
{
for(int k=j+1;k<nos.size();k++)//always maintain
condition that i<j and simply compare the numbers.
{
if(nos[j] > nos[k])
{
spc++;//compute special pair.
}
}
}
Every nos[i] contains the array for which special pair is to be computed.
Is there a way to do this with using a single loop? Or any other logic
that can be time saving and is faster. Thanks in advance I seek to learn
more from this.
And can you please tell me how I can determine which code is faster
without having to execute the code. Your inputs are really welcome.
The main question is to compute the no.of special pairs. Thus, just the
increment of spc.
No comments:
Post a Comment