2654. Minimum Number of Operations to Make All Array Elements Equal to 1 #2411
-
|
Topics: You are given a 0-indexed array
Return the minimum number of operations to make all elements of The gcd of two integers is the greatest common divisor of the two integers. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to find the minimum number of operations to make all array elements equal to 1. Approach:
Let's implement this solution in PHP: 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function minOperations($nums) {
$n = count($nums);
// Count number of 1s in the array
$countOnes = 0;
foreach ($nums as $num) {
if ($num == 1) {
$countOnes++;
}
}
// If there's at least one 1, we can spread it to other elements
if ($countOnes > 0) {
return $n - $countOnes;
}
// Find the minimum length subarray with GCD = 1
$minLength = PHP_INT_MAX;
for ($i = 0; $i < $n; $i++) {
$currentGcd = $nums[$i];
for ($j = $i + 1; $j < $n; $j++) {
$currentGcd = gcd($currentGcd, $nums[$j]);
if ($currentGcd == 1) {
$minLength = min($minLength, $j - $i + 1);
break;
}
}
}
// If no subarray with GCD = 1 exists, return -1
if ($minLength == PHP_INT_MAX) {
return -1;
}
// Operations to create first 1: (minLength - 1)
// Operations to spread 1 to remaining elements: (n - 1)
return ($minLength - 1) + ($n - 1);
}
/**
* Helper function to calculate GCD
*
* @param $a
* @param $b
* @return int|mixed
*/
function gcd($a, $b) {
while ($b != 0) {
$temp = $b;
$b = $a % $b;
$a = $temp;
}
return $a;
}
// Test cases
$nums1 = [2, 6, 3, 4];
$nums2 = [2, 10, 6, 14];
echo "Input: [2,6,3,4] => Output: " . minOperations($nums1) . PHP_EOL;
echo "Input: [2,10,6,14] => Output: " . minOperations($nums2) . PHP_EOL;
?>Explanation:
Time Complexity: O(n² * log(max(nums))) - We check O(n²) subarrays and calculate GCD for each. Space Complexity: O(1) - We only use a constant amount of extra space. Let's test with the examples:
|
Beta Was this translation helpful? Give feedback.
We need to find the minimum number of operations to make all array elements equal to 1.
Approach:
If there's already at least one 1 in the array: I can spread the 1 to adjacent elements, so the answer would be
n - count_of_ones.If there's no 1 in the array: I need to first create a 1, then spread it. To create a 1, I need to find the smallest subarray whose GCD is 1. The number of operations to create a 1 from a subarray of length
kisk-1, then I needn-1more operations to spread it to all elements.Let's implement this solution in PHP: 2654. Minimum Number of Operations to Make All Array Elements Equal to 1