Skip to content

Commit

Permalink
Create 2779. Maximum Beauty of an Array After Applying Operation (#658)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Dec 11, 2024
2 parents 29548fc + 1551b2f commit 45cc82d
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions 2779. Maximum Beauty of an Array After Applying Operation
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
class Solution {
public:
int maximumBeauty(vector<int>& 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<int> 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;
}
};

0 comments on commit 45cc82d

Please sign in to comment.