Java one line O(1) simple solution with explanation


  • 0

    We want to find x such that x * (x + 1) / 2 < n
    We can solve x^2 + x - 2n = 0 and floor(x) is the answer
    The above equation is the same as (x + 1/2)^2 = 2n + 1/4
    Then it follows that x = sqrt(2n + 1/4) - 1/2

        public int arrangeCoins(int n) {
            return (int) (Math.sqrt(2.0 * n + 0.25) - 0.5);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.