Week of Code 35 Lucky Purchase Help

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;
}

This line:

string name[100];

You are getting segmentation faults because of this as n could be till 10^5. Replace it with

string name[n];

For a simple and straightforward approach, and some suggestions on how could one approach CP problems, here is a link to my unofficial editorial. I had time to write editorials for first two problems only. If you need other editorials as well, please let me know.

1 Like

Thanks bro… Can you please write the editorial for the 3D surface area problem

Ok, will prepare it tonight. Please check my blog tomorrow.

Ok… I replaced to string name[n] but still there are few segmentation faults in my code :frowning:

Change “long long price[INT8_MAX];” to long long price[n]; as INT8_MAX = 256

And “ans = INT8_MAX;” to ans = LLONG_MAX; and include limits.h or just include all by including bits/stdc++.h

did that… Got AC… THanks… Will be checking your blog tomorrow :)…
Also do upload ‘unofficial editorials’ from other sites too…

#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
int n;cin>>n;
string ola;ll op=9999999999,price;
while(n–)
{
string lap;ll pr,f=0,s=0,l=0;cin>>lap>>price;pr=price;
while(pr!=0)
{
int rem=pr%10;
if(rem==4)f++;
else if(rem==7)s++;l++;
pr/=10;
}
if(f==s&&(f+s==l)&&price<op){
ola=lap;op=price;
}
//cout<<op<<" “;
}if(op==9999999999)cout<<”-1"<<endl;
else cout<<ola<<endl;
}
hope it will help.