Minimum Division Operations to Make Array Non-Decreasing

Problem Description

Welcome to the world of arrays, where numbers are supposed to be in a nice, orderly fashion, just like your sock drawer (which we all know is a complete disaster). The problem at hand is to make an array non-decreasing by performing the minimum number of division operations. Yes, you heard it right! We’re talking about dividing numbers like they’re pizza slices at a party—only this time, you want to make sure everyone gets a piece without any complaints.

Imagine you have a row of friends, and each one has a certain number of candies. If one friend has more candies than the next, they might get a bit too cocky and start bragging. To avoid this candy-related drama, you need to make sure that no friend has more candies than the one next to them. But how do you do that? By dividing their candies, of course!

So, the challenge is to figure out how many times you need to divide the numbers in the array to keep the peace.

Code Solution


class Solution {
 public:
  int minOperations(vector& nums) {
    int ans = 0;

    for (int i = nums.size() - 2; i >= 0; --i)
      if (nums[i] > nums[i + 1]) {
        const int minDivisor = getMinDivisor(nums[i]);
        if (minDivisor > nums[i + 1])
          return -1;
        nums[i] = minDivisor;
        ++ans;
      }

    return ans;
  }

 private:
  int getMinDivisor(int num) {
    for (int divisor = 2; divisor <= sqrt(num); ++divisor)
      if (num % divisor == 0)
        return divisor;
    return num;
  }
};

Approach Explanation

The code works by iterating through the array from the second-to-last element to the first. If it finds an element that is greater than the one following it, it calculates the minimum divisor of that element. If this divisor is greater than the next element, it returns -1 (because, let’s face it, you can’t divide your way out of that mess). Otherwise, it updates the current element to this divisor and increments the operation count.

Time and Space Complexity

Time Complexity: O(n * sqrt(m)), where n is the number of elements in the array and m is the maximum value in the array. This is because for each element, we may need to check up to the square root of its value to find the minimum divisor.

Space Complexity: O(1), as we are using a constant amount of extra space.

Real-World Example

Let’s say you’re at a party with your friends, and everyone has a different number of snacks. If one friend has 10 snacks and the next has 5, you can’t have that! You need to divide the 10 snacks into smaller portions until they’re equal or less than 5. This is exactly what the algorithm does—ensuring that no one has more than their neighbor, thus keeping the snack-related peace.

Similar Problems

3-Sum Solution in C++