[JAVA] 3 lines. Building solution from the ground up


  • 0
    M

    I found this pattern:

    1 -> 1
    3 -> 2
    6 -> 3
    10 -> 4
    15 -> 5
    21 -> 6

    So, basically to build a new row, we need to add the height of the previous row + 1 to our number of coins.

    public int arrangeCoins(int n) {
            
            if (n < 0)
                return -1;
            else if (n == 0)
                return 0;
            else if (n < 3)
                return 1;
            
            int rows = 2;
            long coins = 3;
            
            // loop until coins is bigger than n.
            while (coins <= n) {
                coins = coins + rows + 1;
                rows++;
            }
            
            // return the last number
            return rows-1;
            
        }
    

Log in to reply
 

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