<p>Given a positive integer <code>n</code>,&nbsp;you can apply one of the following&nbsp;operations:</p>

<ol>
	<li>If <code>n</code> is even, replace <code>n</code> with <code>n / 2</code>.</li>
	<li>If <code>n</code> is odd, replace <code>n</code> with either <code>n + 1</code> or <code>n - 1</code>.</li>
</ol>

<p>Return <em>the minimum number of operations needed for</em> <code>n</code> <em>to become</em> <code>1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 8
<strong>Output:</strong> 3
<strong>Explanation:</strong> 8 -&gt; 4 -&gt; 2 -&gt; 1
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 7
<strong>Output:</strong> 4
<strong>Explanation: </strong>7 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1
or 7 -&gt; 6 -&gt; 3 -&gt; 2 -&gt; 1
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> n = 4
<strong>Output:</strong> 2
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

class Solution:
    def integerReplacement(self, n: int) -> int:
        """
        U - Is n guaranteed to be positive?
        M - Memoization, recursion, dp
        P -
        To avoid repeat work, memoize the solution, perhaps using an additional data structure for caching purposes.
        I - 
        initialize a dictionary for caching purposes
        define a recursive helper method (parameter: curr_num)
            if curr_num is already in the cache
                return the cached result
            if curr_num is 1
                return 0
                
            if curr_num is even
                call the function recursively, adding one to the number of operations for the curr_num
            if curr_num is odd
                call the function recursively, taking the largest of the recursive calls on (n + 1) and (n - 1)
                
            return the number of operations for curr_num
            
        return the result of the recursive call on n
        R - 
        E - 
        """
        
        cache = defaultdict(int)
        def helper(curr_num):
            # print(curr_num, cache[curr_num])
            if curr_num in cache:
                return cache[curr_num]
            if curr_num <= 1:
                return 0
            
            if curr_num % 2 == 0:
                cache[curr_num] = 1 + helper(curr_num // 2)
            else:
                cache[curr_num] = min(1 + helper(curr_num - 1), 1 + helper(curr_num + 1))
                
            return cache[curr_num]
        
        return helper(n)
16800