From 1551b2fe1308c5a9111952d2aab0a4f35bb1f59a Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Wed, 11 Dec 2024 15:18:05 +0530 Subject: [PATCH] Create 2779. Maximum Beauty of an Array After Applying Operation --- ...eauty of an Array After Applying Operation | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 2779. Maximum Beauty of an Array After Applying Operation diff --git a/2779. Maximum Beauty of an Array After Applying Operation b/2779. Maximum Beauty of an Array After Applying Operation new file mode 100644 index 0000000..b4643fa --- /dev/null +++ b/2779. Maximum Beauty of an Array After Applying Operation @@ -0,0 +1,56 @@ +class Solution { +public: + int maximumBeauty(vector& nums, int k) { + + // Find the minimum and maximum values + int min = INT_MAX; + int max = INT_MIN; + + for (int i = 0; i < nums.size(); i++) + { + // Add max and min as standard library + min = std::min(min, nums[i]); + max = std::max(max, nums[i]); + } + + // Setting for range + // 100000 is constrains, maximum value in nums + k, since values are in [0, 100000] + // Since the maximum value in nums[] can be up to 100000 and k can also be as large as 100,000 + int max_total = std::min(100000, max + k); + int min_total = std::max(0, min - k); + // Setting frequency array and update later + int range = max_total - min_total + 1; + std::vector freq(range, 0); + + // Updating frequency array + for (int i = 0; i < nums.size(); i++) + { + int left = std::max(min_total, nums[i] - k); + int right = std::min(max_total, nums[i] + k); + freq[left - min_total]++; + + // Mark the end of range in the frequency array freq[] + if (right + 1 <= max_total) + { + freq[right + 1 - min_total]--; + } + } + + int current_beauty = 0; + int max_beauty = 0; + + // Calculate maximum beauty + for (int i = 0; i < range; i++) + { + current_beauty += freq[i]; + max_beauty = std::max(max_beauty, current_beauty); + // If beauty reaches the length of nums, return + if (max_beauty == nums.size()) + { + return max_beauty; + } + } + // Return result + return max_beauty; + } +};