LeetCode-in-Java

390. Elimination Game

Medium

You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:

Given the integer n, return the last number that remains in arr.

Example 1:

Input: n = 9

Output: 6

Explanation:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr = [2, 4, 6, 8]
arr = [2, 6]
arr = [6]

Example 2:

Input: n = 1

Output: 1

Constraints:

Solution

public class Solution {
    public int lastRemaining(int n) {
        return n == 1 ? 1 : 2 * (n / 2 - lastRemaining(n / 2) + 1);
    }
}