From e35eb0803d2b8b006bd7b35ffe0324c3f4ae5b9d Mon Sep 17 00:00:00 2001 From: mukul96 Date: Sun, 6 Nov 2022 23:48:11 +0530 Subject: [PATCH] added Maximum Sum of Distinct Subarrays With Length K problem --- ...um of Distinct Subarrays With Length K.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Hashing/Maximum Sum of Distinct Subarrays With Length K.cpp diff --git a/Hashing/Maximum Sum of Distinct Subarrays With Length K.cpp b/Hashing/Maximum Sum of Distinct Subarrays With Length K.cpp new file mode 100644 index 0000000..31f78c4 --- /dev/null +++ b/Hashing/Maximum Sum of Distinct Subarrays With Length K.cpp @@ -0,0 +1,51 @@ +class Solution +{ +public: + long long maximumSubarraySum(vector &nums, int k) + { + long long maxSum = 0; + long long sumOfCurr = 0; + unordered_map 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; + } +}; \ No newline at end of file