Skip to content

Commit

Permalink
Create Largest Subarray with Sum X
Browse files Browse the repository at this point in the history
dorakit#15 Issue resolved
  • Loading branch information
kingrishabdugar authored Oct 1, 2021
1 parent 342d0c9 commit b3ab944
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Largest Subarray with Sum X
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include<bits/stdc++.h>
using namespace std;
int largestSubarrayWithSumX(int arr[],int n,int x)
{
int prefix_sum=0;
int res=0;
unordered_map<int,int>mp;
for(int i=0;i<n;i++)
{
prefix_sum+=arr[i];
if (prefix_sum==x)
res=i+1;
if(mp.find(prefix_sum)==mp.end())
mp.insert({prefix_sum,i});
if(mp.find(prefix_sum-x)!=mp.end())
res=max(res,(i-mp[prefix_sum-x]));
}
return res;
}
int main()
{
int arr[] = {8, 3, -7, -4, 1};
int n = sizeof(arr)/sizeof(arr[0]);
int sum = -10;

cout << largestSubarrayWithSumX(arr, n, sum);
}

0 comments on commit b3ab944

Please sign in to comment.