2779. Maximum Beauty of an Array After Applying Operation #941
-
Topics: You are given a 0-indexed array In one operation, you can do the following:
The beauty of the array is the length of the longest subsequence consisting of equal elements. Return the maximum possible beauty of the array Note that you can apply the operation to each index only once. A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can utilize sorting and a sliding window approach. Approach:
Let's implement this solution in PHP: 2779. Maximum Beauty of an Array After Applying Operation <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function maximumBeauty($nums, $k) {
// Sort the array
sort($nums);
$maxBeauty = 0; // To store the maximum beauty found
$i = 0; // Sliding window start index
// Iterate over the array with `j` as the end index of the window
for ($j = 0; $j < count($nums); $j++) {
// Check if the difference is within the allowed range
while ($nums[$j] - $nums[$i] > 2 * $k) {
$i++; // Shrink the window from the left
}
// Update the maximum beauty (window size)
$maxBeauty = max($maxBeauty, $j - $i + 1);
}
return $maxBeauty;
}
// Example Usage:
$nums1 = [4, 6, 1, 2];
$k1 = 2;
echo maximumBeauty($nums1, $k1) . "\n"; // Output: 3
$nums2 = [1, 1, 1, 1];
$k2 = 10;
echo maximumBeauty($nums2, $k2) . "\n"; // Output: 4
?> Explanation:
Complexity Analysis:
Examples:Input 1:$nums = [4, 6, 1, 2];
$k = 2;
echo maximumBeauty($nums, $k); // Output: 3 Input 2:$nums = [1, 1, 1, 1];
$k = 10;
echo maximumBeauty($nums, $k); // Output: 4 This solution adheres to the constraints and efficiently computes the result for large inputs. |
Beta Was this translation helpful? Give feedback.
We can utilize sorting and a sliding window approach.
Approach:
Let's implement this solution in PHP: 2779. Maximum Beauty of an Array After Applying Operation