-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 2779. Maximum Beauty of an Array After Applying Operation (#658)
- Loading branch information
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |