I had participated in Hackerrank Week of Code 35 and came across this question. I couldn’t get full points on this as it showed segmentation fault while evaluation. But, when the editorials came out, I found my solution to be somewhat matching with that of the editorial. Please help in pointing out my mistake.
Here’s my code:
#include
using namespace std;
bool isValid(long long n)
{
long long temp;
temp = n;
int c[2] = {0};
while(n != 0)
{
temp = n%10;
if(temp != 4 && temp != 7)
return 0;
if(temp == 4)
c[0]++;
else if(temp == 7)
c[1]++;
n = n/10;
}
if(c[0] == c[1])
{
return 1;
}
else
return 0;
}
int main()
{
long long n;
cin>>n;
long long ans,index;
ans = INT8_MAX;
string name[100];
bool flag = false;
long long price[INT8_MAX];
for(long long i=0;i<n;i++)
{
cin>>name[i];
cin>>price[i];
}
for(long long i=0;i<n;i++)
{
if(isValid(price[i]))
{
flag = true;
if(price[i] < ans)
{
ans = price[i];
index = i;
}
}
}
if(flag)
{
cout<<name[index];
}
else
cout<<"-1";
return 0;
}