DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Minimum Division Operations to Make Array Non Decreasing

Problem

class Solution {
    //one thing to note here is we have to get the values in increasing order,
    //the current values of nums[i] is the max value it can have after which it can only get a lower value.
    //start from the second last value in nums[] because last values is already the largest it can be

    public int minOperations(int[] nums) {
        int count = 0;
        //compare value at i-1th index with value at i, index if it is greater, update the value at i-1th index with its greatest divisor, if you get 1 as greatest divisor return -1;
        for (int i = nums.length-1; i >0; i--) {
            while (nums[i] < nums[i-1]) {
                int g = gd(nums[i-1]);
                if(g ==1){
                    return -1;
                }
                nums[i-1] = g;
                count++;
            }
        }
        return count;
    }
    // it will give the greatest possible divisor else 1
     public int gd(int n) {
        int d = 1;
        for (int i = 2; i<=Math.sqrt(n); i++) {
            if (n % i == 0) {
                return i;
            }
        }
        return d; 
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)