Skip to content
Discussion options

You must be logged in to vote

We need to find the minimum number of operations to make all array elements equal to 1.

Approach:

  1. 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.

  2. 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 k is k-1, then I need n-1 more 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

<?php
/**
 * @param Integer[] $nums
 * @return Integer
 */
function minO…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Nov 12, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants