Help with ZCO14003

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    long long int maxP=-1;
    vector<int> v(n);
    for(long long int i=0;i<n;i++)
        cin>>v[i];
    sort(v.begin(),v.end());
    for(long long int i=0;i<n;i++){
        long long int c=(n-i)*v[i];
        maxP=max(maxP,c);
    }
    cout<<maxP;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    long long int maxP=-1;
    vector<int> v(n);
    for(int i=0;i<n;i++)
        cin>>v[i];
    sort(v.begin(),v.end());
    for(int i=0;i<n;i++){
        long long int c=(n-i)*v[i];
        maxP=max(maxP,c);
    }
    cout<<maxP;
    return 0;
}

QUESTION LINK
Why the first code works and not the second(despite the fact that maximum value of N is 5*10^5 ) ?

Variable t wasn’t declared, so both codes give compilation error.

1 Like

@anon49701446 Actually the whole coding was done in parameter ‘t’, while writing here I changed it to ‘n’. The ‘t’ with vector remained unnoticed. So, consider that I do not have any compilation error w.r.t. any parameter not defined. Help me why I am getting answer in first code, while not in second code.
Thanks

In second code you are multiplying “int” and “int” which results in “int” and storing in long long int. So,overflow had happened, resulting in wa

2 Likes

@sebastian Thanks brother

Can you specify the line where int and long long int are multiplied please. I am not able to figure it out.

for(int i=0;i<n;i++){
        long long int c=(n-i)*v[i];
        maxP=max(maxP,c);
    }

thanks for your help but I am surprise there are some coders who also notice this thing.
At first I also not notice this.

Bro , I have made same mistake two to three times. So, now its like I started noticing.