30. Minimum Replacements to Sort the Array
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
The intution to solve this question is we can make all the element in the vector eqaul and also try to keep the replacement number as small as possible , we can achive this as :
Initialize variables:
curmax
to keep track of the current maximum value (initialized to INT_MAX
).
ans
to keep track of the minimum number of replacements (initialized to 0).
Start a loop from the last element (i
initialized to n-1
) and move backwards towards the first element.
Inside the loop, check if nums[i]
is less than or equal to curmax
. If it is, update curmax
to nums[i]
. This step ensures that curmax
always represents the maximum value encountered so far.
If nums[i]
is greater than curmax
, it means a replacement is needed to make them equal. Calculate the number of replacements required as follows:
If nums[i]
is divisible by curmax
, subtract 1 from the result and add it to ans
.
Otherwise, divide nums[i]
by curmax
to get div
, then add div
to ans
. Update curmax
by dividing nums[i]
by div
, which ensures that curmax
represents the maximum value encountered after the replacement.
Repeat steps 3-4 for all elements in the vector from right to left.
Time Complexity: O(n)
Auxiliary Space Complexity: O(1)
because we used an extra queue..
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.