30. Minimum Replacements to Sort the Array
The problem can be found at the following link: Question Link
My Approach
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 toINT_MAX
).ans
to keep track of the minimum number of replacements (initialized to 0).
Start a loop from the last element (
i
initialized ton-1
) and move backwards towards the first element.Inside the loop, check if
nums[i]
is less than or equal tocurmax
. If it is, updatecurmax
tonums[i]
. This step ensures thatcurmax
always represents the maximum value encountered so far.If
nums[i]
is greater thancurmax
, it means a replacement is needed to make them equal. Calculate the number of replacements required as follows:If
nums[i]
is divisible bycurmax
, subtract 1 from the result and add it toans
.Otherwise, divide
nums[i]
bycurmax
to getdiv
, then adddiv
toans
. Updatecurmax
by dividingnums[i]
bydiv
, which ensures thatcurmax
represents the maximum value encountered after the replacement.
Repeat steps 3-4 for all elements in the vector from right to left.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)
Auxiliary Space Complexity:
O(1)
because we used an extra queue..
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 rishabhv12/Daily-Leetcode-Solution repository.
Last updated