2020 Updated Picking Numbers Hackerrank Solution by Coding Demons

    

       Coding Demons has solved Picking Numbers a problem on Hackerrank. The Solution is given in two stages.

Stage 1 Logic

Stage 2 Code

                    


For better understanding refer our YouTube Tutorial Video.     


LOGIC 

  • Take array size (N)
  • Input array (A)
  • Sort the array.
  • Set position and max equal to 0, set count to 1.
  • Take the difference of two elements and check the condition.
  • If condition true then increment count.
  • Else check for maximum value between max and count store the same in max.
  • Print the maximum of max and count.



CODE

/***SOLUTION BY CODING DEMONS***/

#include<bits/stdc++.h>
using namespace std;

int main () {

int n;   //array size
cin>>n;

int a[n];  //array
for (int i=0;i<n;i++) cin>>a[i];

int pos=0,max=0,count=1;    

//sort the array     
int x = sizeof(a)/sizeof(a[0]);  
 sort(a, a+x);

for (int i=1;i<n;i++){    

 int d=a[i]-a[pos];  
//check the difference

 if (d<=1) count++;     
//if less than or equal increment count

 else {
  if(count>max) max=count;
//else check for max between count 
//and max and store the maximum in max     

  pos=i;
  count=1;
  }
}
if (count>max) max=count;   
 //Again check for max between count 
//and max and store the maximum in max

cout<<max;  //print max

return 0;
}


/*** END ***/

Our other Code Solutions
  1.  Cats and a Mouse
  2.  For More Solutions Click Here




!! SUBSCRIBE FOR MORE CODES & VIDEOS !!

Post a Comment

0 Comments