3375. Minimum Operations to Make Array Values Equal to K #1538
-
Topics: You are given an integer array An integer For example, if You are allowed to perform the following operation on
Return the minimum number of operations required to make every element in Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the minimum number of operations required to make all elements of an array equal to a given integer Approach
Let's implement this solution in PHP: 3375. Minimum Operations to Make Array Values Equal to K <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function minOperations($nums, $k) {
foreach ($nums as $num) {
if ($num < $k) {
return -1;
}
}
$unique_gt = array();
foreach ($nums as $num) {
if ($num > $k) {
$unique_gt[$num] = true;
}
}
return count($unique_gt);
}
// Example 1
print_r(minOperations(array(5, 2, 5, 4, 5), 2)); // Output: 2
// Example 2
print_r(minOperations(array(2, 1, 2), 2)); // Output: -1
// Example 3
print_r(minOperations(array(9, 7, 5, 3), 1)); // Output: 4
?> Explanation:
This approach efficiently determines the minimum operations by leveraging the distinct values greater than |
Beta Was this translation helpful? Give feedback.
We need to determine the minimum number of operations required to make all elements of an array equal to a given integer
k
. Each operation involves selecting a valid integerh
such that all elements greater thanh
are reduced toh
. The solution must also check if it is impossible to achieve this goal and return-1
in such cases.Approach
k
, it is impossible to make all elements equal tok
because we cannot increase values. In this case, return-1
.k
. Each distinct value represents a step where we can reduce the elements to the…