Skip to content

Commit

Permalink
added Maximum Sum of Distinct Subarrays With Length K problem
Browse files Browse the repository at this point in the history
  • Loading branch information
mukul96 committed Nov 6, 2022
1 parent 6663c1b commit e35eb08
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Hashing/Maximum Sum of Distinct Subarrays With Length K.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Solution
{
public:
long long maximumSubarraySum(vector<int> &nums, int k)
{
long long maxSum = 0;
long long sumOfCurr = 0;
unordered_map<int, int> mp;
int n = nums.size();
int countOfSame = 0;
for (int i = 0; i < k; i++)
{
if (mp[nums[i]] > 0)
{
countOfSame++;
}
mp[nums[i]] += 1;
sumOfCurr += nums[i];
}

if (countOfSame == 0)
{
maxSum = max(sumOfCurr, maxSum);
}
int i = k;
while (i < n)
{
sumOfCurr -= nums[i - k];
if (mp[nums[i - k]] > 1)
{
countOfSame--;
}
mp[nums[i - k]] -= 1;

if (mp[nums[i]])
{
countOfSame++;
}
mp[nums[i]] += 1;
sumOfCurr += nums[i];

if (countOfSame == 0)
{
maxSum = max(sumOfCurr, maxSum);
}
i++;
}

return maxSum;
}
};

0 comments on commit e35eb08

Please sign in to comment.