Coursera's Algorithmic toolbox assignment solutions( Car Fueling, Maximum Advertisement Revenue ) :

Problem 3: Car Fueling

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 d,m,n,i,nr=0,cr=0,lr; //d=distance between the cities , cr=currentrefill,
cin>>d>>m>>n; // m=max. distance by the car in a full tank
long long a[n+1]; //lr=lastrefill , nr=no. of refills
a[0]=0; // array a represents gas stations positions
for(i=1;i<=n;i++)
{
cin>>a[i];
}
a[n+1]=d;
while(cr<=n) //this algorithm is explained perfectly
{ //in the lecture
lr=cr;
while(cr<=n && a[cr+1]-a[lr]<=m)
{
cr=cr+1;
}
if(cr==lr)
{
cout<<"-1"<<endl;
break;
}
if(cr<=n)
{
nr=nr+1;
}
}
if(cr!=lr)
{
cout<<nr<<endl;
}
}

This code is simple. There's no need for any explanation.





Problem 4: Maximum Advertisement Revenue

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,j,k,res=0;
    cin>>n;
    long long a[n],b[n];
    for(i=0;i<n;i++)
{
cin>>a[i];
}
for(j=0;j<n;j++)
{
cin>>b[j];
}
sort(a,a+n); //see note below
sort(b,b+n);
for(k=0;k<n;k++)
{
res+=a[k]*b[k];
}
cout<<res;
}

Since we want to maximize the sum of the products , what we can do is first we will select the maximum element from array a and multiply it to the maximum element of array b and then we will select the second maximum element from array a and multiply it to the second maximum element of the array b and repeat this procedure and add each product to get the maximum result.




Guys , if you have any queries related to a question or need more explanation, comment down 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 ) :