Digit Operations to Make Two Integers Equal

You are given two integers n and m that consist of the same number of digits.

You can perform the following operations any number of times:

  • Choose any digit from n that is not 9 and increase it by 1.
  • Choose any digit from n that is not 0 and decrease it by 1.

The integer n must not be a prime number at any point, including its original value and after each operation.

The cost of a transformation is the sum of all values that n takes throughout the operations performed.

Return the minimum cost to transform n into m. If it is impossible, return -1.

Example 1
Inputn = 10, m = 12
Output85
One valid minimum-cost sequence is 10 -> 20 -> 21 -> 22 -> 12, whose summed values are 10 + 20 + 21 + 22 + 12 = 85.
Example 2
Inputn = 4, m = 8
Output-1
It is impossible to make n equal to m.

Constraints

  • 1 <= n, m < 10^4
  • n and m consist of the same number of digits.

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate