Longest subarray with sum exactly equal to k

Is the code correct for all integers positive and negative?

#include <bits/stdc++.h>

using namespace std;

int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);

long int n;
cin>>n;
long int k;
cin>>k;
long long int a[n],i,len=0,sum=0;
unordered_map<long long int,int> m;
m[0]=-1;
for(i=0;i<n;++i)
    cin>>a[i];

for(i=0;i<n;++i)
  {
      sum+=a[i];
      if(m.find(sum)==m.end())
         m[sum]=i;
         
      if(m.find(sum-k)!=m.end() && len<i-m[sum-k])
         {
             len=i-m[sum-k];
            
         }
  }
   
   cout<<len;      

 return 0;

}

format your code ``` before and after code.

is it correct though?

please tell me guys

You missed the condition,
When subarray starts from 0th index, so put the conditon-

         if(sum==k){
              len=i+1;
        }

oh okay!.So everything else is okay ?.Even for negative numbers?.

Yup, seems fine to me.

hey but i just rechecked with the code…i didn’t understand why does it fail for subarray starting with index 0.
can you give me an example?

hey but i have handled that case in this statement
m[0]=-1;
just check once and let me know.

My bad, I missed that statement. The code is perfect

oh okay thank you!.