Collatz Sequence
1. **Problem Statement:** Given a positive integer $N$, find the starting number $\leq N$ that produces the longest Collatz sequence chain. If multiple numbers have the same longest chain length, return the maximum such number.
2. **Collatz Sequence Rules:**
- If $n$ is even, the next term is $\frac{n}{2}$.
- If $n$ is odd, the next term is $3n + 1$.
3. **Chain Length Definition:** The length of the chain is the number of terms from the starting number down to 1, inclusive.
4. **Approach:**
- For each number $1 \leq k \leq N$, compute the length of its Collatz sequence.
- Use memoization to store chain lengths for numbers already computed to avoid redundant calculations.
- Track the number with the longest chain length up to each $N$.
5. **Example:** For $n=9$, the sequence is:
$$9 \to 28 \to 14 \to 7 \to 22 \to 11 \to 34 \to 17 \to 52 \to 26 \to 13 \to 40 \to 20 \to 10 \to 5 \to 16 \to 8 \to 4 \to 2 \to 1$$
which has 20 terms.
6. **Algorithm Steps:**
- Initialize an array `lengths` to store chain lengths for numbers up to $5 \times 10^6$.
- For each number from 1 to max $N$ in input, compute chain length using recursion and memoization.
- Maintain an array `max_num` where `max_num[i]` stores the number $\leq i$ with the longest chain.
- For each test case, output `max_num[N]`.
7. **Complexity:**
- Preprocessing all chain lengths up to $5 \times 10^6$ is efficient with memoization.
- Query answering is $O(1)$ after preprocessing.
**Final answer:** For each input $N$, print the number $\leq N$ with the longest Collatz chain length, choosing the maximum number if ties occur.