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:
curmaxto keep track of the current maximum value (initialized toINT_MAX).ansto keep track of the minimum number of replacements (initialized to 0).
Start a loop from the last element (
iinitialized 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, updatecurmaxtonums[i]. This step ensures thatcurmaxalways 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]bycurmaxto getdiv, then adddivtoans. Updatecurmaxby dividingnums[i]bydiv, which ensures thatcurmaxrepresents 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++)
class Solution {
public:
long long minimumReplacement(vector<int>& nums) {
int n=nums.size();
int curmax=INT_MAX;
long long ans=0;
for(int i=n-1; i>=0; i--){
if(nums[i]<=curmax){
curmax=nums[i];
}
else{
if(nums[i]%curmax==0){
ans+=((nums[i]/curmax)-1);
}else{
ans+=((nums[i]/curmax));
int div=(nums[i]/curmax)+1;
curmax=nums[i]/div;
}
}
}
return ans;
}
};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
Was this helpful?