LeetCode 3326: Minimum Division Operations to Make Array Non Decreasing

Problem Description

Explanation

To solve this problem, we can iterate through the array from left to right. For each element, we need to check if it is possible to make it non-decreasing considering the previous elements. If the current element is smaller than the previous element, we need to calculate the number of operations required to make it non-decreasing.

We need to find the greatest proper divisor of the current element that is less than or equal to the previous element. If such a divisor exists, we can perform the operation and update the current element. If no such divisor is found, it is not possible to make the array non-decreasing, and we return -1.

The time complexity of this approach is O(n * sqrt(max(nums))) where n is the number of elements in the array and max(nums) is the maximum value in the array. The space complexity is O(1) as we are not using any extra space.

Solutions

class Solution {
    public int minOperations(int[] nums) {
        int operations = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] < nums[i - 1]) {
                int divisor = nums[i - 1] / nums[i];
                if (nums[i - 1] % nums[i] != 0) {
                    divisor++;
                }
                int potential = (int) Math.pow(divisor, (int) (Math.log(nums[i]) / Math.log(divisor)));
                if (nums[i] * potential > nums[i - 1]) {
                    return -1;
                }
                operations += (int) (Math.log(nums[i]) / Math.log(divisor));
            }
        }
        return operations;
    }
}

Loading editor...