Home > OS >  This logic should find the number of pairs in array with difference d but only the sample test case
This logic should find the number of pairs in array with difference d but only the sample test case

Time:12-10

For this array(sample test case): 1 1 2 2 4 6 and D = 2 the number of pairs with difference D is 3. Explanation: Here the pairs of difference 2 are (2,4) and (4,6). There are 2 ways to generate (2,4) and there is 1 way to generate 4,6. The output is 3 (1 2). This code pass this test case only but it doesn't pass all other test cases (about 13 hidden test cases). I need to understand why does this happen

int Func_M_2(vector<int> arr,int D)
{
    int counter =0;
    for(int i=0;i<arr.size();i  )
        {
            for(int j=i 1;j<arr.size();j  )
            {
                if(arr[j]-arr[i]==D)
                counter  ;
            }
        }
return counter;
}

CodePudding user response:

Sorry I cannot post a comment but I think the difference D must also be abs(D) in your if():

if( abs(arr[j]-arr[i]) == abs(D) )

CodePudding user response:

I can offer the solution of your problem.

#include <iostream>
#include <vector>
using namespace std;
void solve()
{
    int difference=2;
    vector<int> numbers={1, 1, 2, 2, 4, 6};
    vector<int> vectorCount;
    for(int i=0; i<numbers.size();   i)
    {
        int count=0;
        for(int j=0; j<numbers.size();   j)
        {
            if(numbers[i]-numbers[j]==difference)
            {
                  count;
            }
        }
        vectorCount.push_back(count);
    }
    int summarize=0;
    for(int i=0; i<vectorCount.size();   i)
    {
        summarize =vectorCount[i];
    }
    cout<<"summarize <- "<<summarize<<endl;
    return;
}
int main()
{
    solve();
    return 0;
}

Here is the result:

summarize <- 3
  • Related