-1
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <utility>
#include <functional>
#include <cmath>
#include <climits>
using namespace std;

#define pb push_back
#define mp make_pair
#define ll long long 


int main (void)
{
    int i,j,k,n;
    int arr[500001];
    long long ans[500001];
    int val = INT_MIN;
    cin>>n;
    for ( i = 0; i < n; i++ )
    {
        cin>>arr[i];
        if (val < arr[i])
            val = arr[i];
    }
    long long count[500001];
    for ( i = 0; i < n; i++ )
        count[arr[i]]++;
    //int ans = INT_MIN;
    ans[0] = 0;
    ans[1] = count[1];
    for ( i = 2; i <= val; i++ )
    {
        ans[i] = max(ans[i-1],ans[i-2]+count[i]*i);
    }
    cout<<ans[val]<<"\n";
    return 0;
}

So, I implemented this simple code, where in I declare 3 arrays and try to tweak a little bit according to my question (which is a separate thing altogether). But as soon as I start up this code, I am shown a segmentation fault. I don't know why? Why is it happening? I tried to run it through the debugger and it shows a possible error in the max function. Hence I made my own maxi function but it still shows a segmentation fault?

Edit: On using the debugger, it shows the following:

template <class _Tp, class _Compare>
inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
const _Tp&
max(const _Tp& __a, const _Tp& __b, _Compare __comp)
{
    return __comp(__a, __b) ? __b : __a;
}

Thread 1: EXC BAD_ACCESS (code=2, address=0x7fff5f276154)

rohansingh
  • 327
  • 3
  • 12

1 Answers1

0

There should be stack overflow.

Consider allocating enough and not excessive memory using new[].

For temporary fix, add static before int or long long to the three very large arrays.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70