LeetCode 441 Arranging Coins (Python)

Posted by 小明MaxMing on July 1, 2020

题目

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

Given n, find the total number of full staircase rows that can be formed.

n is a non-negative integer and fits within the range of a 32-bit signed integer.

解题思路

1 + 2 + ... + k <= N
先转换成等式
k = (-1+sqrt(1+8*n))/2
最后的答案是k的取整

代码

class Solution:
    def arrangeCoins(self, n: int) -> int:
        return int((-1 + math.sqrt(1 + 8 * n)) / 2)

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅