3396. Minimum Number of Operations to Make Elements in Array Distinct #1533
-
Topics: You are given an integer array
Note that an empty array is considered to have distinct elements. Return the minimum number of operations needed to make the elements in the array distinct. 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 in an array distinct. Each operation involves removing the first three elements from the array, or all remaining elements if there are fewer than three. Approach
Let's implement this solution in PHP: 3396. Minimum Number of Operations to Make Elements in Array Distinct <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function minimumOperations($nums) {
$n = count($nums);
for ($k = 0; ; $k++) {
$start = 3 * $k;
if ($start >= $n) {
return $k;
}
$subarray = array_slice($nums, $start);
$seen = array();
$valid = true;
foreach ($subarray as $num) {
if (isset($seen[$num])) {
$valid = false;
break;
}
$seen[$num] = true;
}
if ($valid) {
return $k;
}
}
}
// Test Cases
print minimumOperations([1, 2, 3, 4, 2, 3, 3, 5, 7]) . "\n"; // Output: 2
print minimumOperations([4, 5, 6, 4, 4]) . "\n"; // Output: 2
print minimumOperations([6, 7, 8, 9]) . "\n"; // Output: 0
?> Explanation:
This approach efficiently checks each possible number of operations in sequence, ensuring the minimum number of operations is found by leveraging early termination when a valid subarray is identified. |
Beta Was this translation helpful? Give feedback.
We need to determine the minimum number of operations required to make all elements in an array distinct. Each operation involves removing the first three elements from the array, or all remaining elements if there are fewer than three.
Approach
k
, check the subarray starting from index3*k
(after removing the first3*k
elements). If this subarray contains all distinct elements, thenk
is the answer.