Minimum Operations to Make the Array Beautiful Problem
Description
LeetCode Problem 3717.
You are given an integer array nums.
An array is called beautiful if for every index i > 0, the value at nums[i] is divisible by nums[i - 1].
In one operation, you may increment any element nums[i] (with i > 0) by 1.
Return the minimum number of operations required to make the array beautiful.
Example 1:
Input: nums = [3,7,9]
Output: 2
Explanation:
Applying the operation twice on nums[1] makes the array beautiful: [3,9,9]
Example 2:
Input: nums = [1,1,1]
Output: 0
Explanation:
The given array is already beautiful.
Example 3:
Input: nums = [4]
Output: 0
Explanation:
The array has only one element, so it's already beautiful.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 50
Solution
Approach: Dynamic Programming over the Previous Value
Let f[v] be the fewest operations so far such that the last processed element ends up equal to v. Start with f = {nums[0]: 0} (the first element cannot be changed).
For the next element x and each state (pre, s), the new value must be a multiple of pre that is at least x. Start at the smallest such multiple, ceil(x / pre) * pre, and step by pre, recording s + (cur - x) for each cur into the new table. Because nums[i] <= 50, an optimal array never needs a value above 100, so the loop stops there. The answer is the smallest value in the final table.
Complexity: O(n * V * log V) time and O(V) space with V = 100.
class Solution:
def minOperations(self, nums: List[int]) -> int:
f = {nums[0]: 0}
for x in nums[1:]:
g = {}
for pre, s in f.items():
cur = (x + pre - 1) // pre * pre
while cur <= 100:
if cur not in g or g[cur] > s + cur - x:
g[cur] = s + cur - x
cur += pre
f = g
return min(f.values())