Skip to content

Latest commit

 

History

History
21 lines (20 loc) · 610 Bytes

31.md

File metadata and controls

21 lines (20 loc) · 610 Bytes

Longest subarray with sum divisible by k

int longSubarrWthSumDivByK(int a[], int n, int k)
	{
	    // Complete the function
	   int sum=0,maxi=0,j=0;
        unordered_map<int,int>mp;
        for(int i=0;i<n;i++){
            sum+=a[i];
            int r=sum%k;
            if(r<0) r+=k;
            if(r==0) maxi=max(maxi,i+1);
            else{
                if(mp.find(r)!=mp.end()) maxi=max(maxi,i-mp[r]);
                else mp[r]=i;
            }
        }
        return maxi;
	}