TCS CODEVITA questions and solutions Given an array of integers A, and an integer K find number of happy elements (2020).

TCS CODE VITA



Count Pairs:

Problem Description Given an array of integers A, and an integer K find a number of happy elements. Element X is happy if there exists at least 1 element whose difference is less than K i.e. an element X is happy if there is another element in the range [X-K, X+K] other than X itself. Constraints 1 <= N <= 10^5 0 <= K <= 10^5 0 <= A[i] <= 10^9 Input First-line contains two integers N and K where N is the size of the array and K is a number as described above Second-line contains N integers separated by space. Output Print a single integer denoting the total number of happy elements. Time Limit 1 Examples Example 1 Input 6 3 5 5 7 9 15 2 Output 5 Explanation Other than number 15, everyone has at least 1 element in the range [X-3, X+3]. Hence they are all happy elements. Since these five are in number, the output is 5. Example 2 Input 3 2 1 3 5 Output 3 Explanation All numbers have at least 1 element in the range [X-2, X+2]. Hence they are all happy elements. Since these three are in number, the output is 3. 

Solution in java:

import java.util.*;
class thir
{
	public static void main(String args[])
	{
		Scanner in=new Scanner(System.in);
		int n=in.nextInt();
		int k=in.nextInt();
		int count=0;
		int[] x=new int[n];
		for(int i=0;i<n;i++)
			x[i]=in.nextInt();
		for(int i=0;i<n;i++)
		{
			int tprev=x[i]-k;
			int tpost=x[i]+k;
			for(int j=0;j<n;j++)
			{
				if(i!=j)
				{
					if(x[j]<=tpost && x[j]>=tprev)
					{
						count++;
						break;
					}
				}
			}
		}  
		System.out.println(count);	
	}
};
This is not a confirmed solution.

Solution in cpp:


#include <iostream>
using namespace std;

int cal(int k,int x,int i);
int X[100],N;

int cal(int k,int x,int i)
{
    int flag=0;
    int s=x-k;
    int l=x+k;
    
    for(int d=0;d<N;d++)
    {
       if(d!=i)
        {
        if(X[d]>=s && X[d]<=l)
          {
              
              flag=1;
              
          }
      }
      
        
    }
    
    return flag;
    
    
}

int main()
{
    int K,no=0;
    
    cin>>N;
    cin>>K;
    
    for(int i=0;i<N;i++)
    {
       cin>>X[i];
    }
   
   for(int j=0;j<N;j++)
   {
       int a=cal(K,X[j],j);
       if(a==1)
       {
          ++no;
       }
   }
   cout<<no;
   
    return 0;
}

No comments:

Post a Comment

If you have any problems related to solutions or any concept please let me know.

Copyright (c) 2020 Custom Programs All Right Reserved

Pages