|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + int maximumBeauty(vector<int>& nums, int k) { |
| 4 | + |
| 5 | + // Find the minimum and maximum values |
| 6 | + int min = INT_MAX; |
| 7 | + int max = INT_MIN; |
| 8 | + |
| 9 | + for (int i = 0; i < nums.size(); i++) |
| 10 | + { |
| 11 | + // Add max and min as standard library |
| 12 | + min = std::min(min, nums[i]); |
| 13 | + max = std::max(max, nums[i]); |
| 14 | + } |
| 15 | + |
| 16 | + // Setting for range |
| 17 | + // 100000 is constrains, maximum value in nums + k, since values are in [0, 100000] |
| 18 | + // Since the maximum value in nums[] can be up to 100000 and k can also be as large as 100,000 |
| 19 | + int max_total = std::min(100000, max + k); |
| 20 | + int min_total = std::max(0, min - k); |
| 21 | + // Setting frequency array and update later |
| 22 | + int range = max_total - min_total + 1; |
| 23 | + std::vector<int> freq(range, 0); |
| 24 | + |
| 25 | + // Updating frequency array |
| 26 | + for (int i = 0; i < nums.size(); i++) |
| 27 | + { |
| 28 | + int left = std::max(min_total, nums[i] - k); |
| 29 | + int right = std::min(max_total, nums[i] + k); |
| 30 | + freq[left - min_total]++; |
| 31 | + |
| 32 | + // Mark the end of range in the frequency array freq[] |
| 33 | + if (right + 1 <= max_total) |
| 34 | + { |
| 35 | + freq[right + 1 - min_total]--; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + int current_beauty = 0; |
| 40 | + int max_beauty = 0; |
| 41 | + |
| 42 | + // Calculate maximum beauty |
| 43 | + for (int i = 0; i < range; i++) |
| 44 | + { |
| 45 | + current_beauty += freq[i]; |
| 46 | + max_beauty = std::max(max_beauty, current_beauty); |
| 47 | + // If beauty reaches the length of nums, return |
| 48 | + if (max_beauty == nums.size()) |
| 49 | + { |
| 50 | + return max_beauty; |
| 51 | + } |
| 52 | + } |
| 53 | + // Return result |
| 54 | + return max_beauty; |
| 55 | + } |
| 56 | +}; |
0 commit comments