Hackerrank's Problem Solving solutions( Counting Valleys, Electronics Shop, Cats and a Mouse ) :

Problem 22: Counting Valleys

Solution: (in c++)


( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)

#include<bits/stdc++.h>
using namespace std;
int main()
{
long long n,i,v=0,lvl=0; //lvl=level , v=valleys
cin>>n;
string s;
cin>>s;
for(i=0;i<s.length();i++)
{
if(s[i]=='U')
{
lvl++;
}
if(s[i]=='D')
{
lvl--;
}
if(lvl==0 && s[i]=='U') //see note below
{
v++;
}
}
cout<<v;
}

It means that "we just came out of a valley" because only then the final level will be zero and s[i]='U' means we just came out of the valley to make level = 0. By counting how many number of time we came out of a valley , we can count the number of valleys.

 

 

 

 

 

 

Problem 23: Electronics Shop

Solution: (in c++)


( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)

#include <bits/stdc++.h>
using namespace std;
int main()
{
long long b,n,m,max=-1,i,j;
cin>>b>>n>>m;
long long k[n],u[m];
for(i=0;i<n;i++)
{
cin>>k[i];
}
for(j=0;j<m;j++)
{
cin>>u[j];
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(k[i]+u[j]<=b) //see note below
{
if(max<=k[i]+u[j]) //important step
{
max=k[i]+u[j];
}
}
}
}
cout<<max;
}

By using two loops we will add each and every keyboard and usb drive pair. If their sum is less than or equal to the budget then we will put this sum in max variable. The second if statement will help us in finding out the maximum value of the sum.

Initially i took max=-1 because in the question it is said that " If it is not possible to buy both items, return -1". Therefore , if no pair found whose sum is less than or equal to his budget max will remain -1 and it will get printed.

Please note : This approach of finding the maximum value from given values is very very useful i.e using an if statement and then making it equal (see above important step).

 

 

 

 

 

 

Problem 24: Cats and a Mouse

Solution: (in c++)


( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)

#include<bits/stdc++.h>
using namespace std;
int main()
{
int q,a,b,c;
cin>>q;
while(q--)
{
cin>>a>>b>>c;
if(abs(c-a)<abs(c-b))
{
cout<<"Cat A"<<endl;
}
else if(abs(c-a)>abs(c-b))
{
cout<<"Cat B"<<endl;
}
else
{
cout<<"Mouse C"<<endl;
}
}
}

 abs means mod. Therefore , the cat which is at less distance from the mouse will get the mouse.





Guys , if you have any queries or need more explanation for something , comment below!

Comments

Popular posts from this blog

Coursera's Algorithmic toolbox assignment solutions( Sum of Two Digits, Maximum Pairwise Product ) :

HackerEarth's basic programming solutions( Seating Arrangement, Zoos, Anagrams ) :

HackerEarth's basic programming solutions( Minimize Cost, Magical Word, Best Index ) :