Minimum Operations to Convert Number

You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal.

You can perform the following operation repeatedly on the number x:

If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following:

  • x + nums[i]
  • x - nums[i]
  • x ^ nums[i] (bitwise-XOR)

Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward.

Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible.

Example 1
Inputnums = [2,4,12], start = 2, goal = 12
Output2
We can go from 2 to 14 to 12 using 2 operations: add 12, then subtract 2.
Example 2
Inputnums = [3,5,7], start = 0, goal = -4
Output2
We can go from 0 to 3 to -4 using 2 operations, and the last operation may leave the range 0 <= x <= 1000.

Constraints

  • 1 <= nums.length <= 1000
  • -10^9 <= nums[i], goal <= 10^9
  • 0 <= start <= 1000
  • start != goal
  • All the integers in nums are distinct.

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