![]() |
VOOZH | about |
Given an array arr[] of size N, the task is to return the minimum number of operations to make the array sorted (in non-decreasing order) by performing the following operation any number of times:
Examples:
Input: arr[] = {4, 3, 2, 1}, N = 4
Output: 6
Explanation: We need to reduce all the elements to 1,
4 => 3 operations are needed to break 4 to all 1s
3 => 2 operations are needed to break 3 to all 1s
2 => 1 operation is needed to break 2 to all 1s
Total operations = 3 + 2 + 1 = 6Input: arr[] = {10, 20, 9}
Output: 3
Explanation: We need to reduce 20 and 10
20 => 2 operations are needed to reduce 20 to 6 + 7 + 7
10 => 1 operation is needed to reduce 10 to 5 + 5
Total operations = 2 + 1 = 3
Approach: To solve the problem follow the below idea:
Traverse the array in reverse order and for each element, check if it is greater than element to its right (the previous element). If the current element is greater, calculate the number of divisions to make it less than or equal to the previous element. Update the previous element to the value that the current element needs to be divided by. Add the number of divisions to the count of operations. After traversing the whole array, return the count.
Below are the steps to implement the above approach:
Below is the implementation for the above approach:
3
Time Complexity: O(N)
Auxiliary Space: O(1)