自学内容网 自学内容网

Leetcode 441. Arranging Coins

Problem

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

Given the integer n, return the number of complete rows of the staircase you will build.

Algorithm

From 1 calculate the m where ∑ i = 1 m i ≤ n < ∑ i = 1 m + 1 i \sum_{i=1}^m i \leq n < \sum_{i=1}^{m+1} i i=1min<i=1m+1i.

Code

class Solution:
    def arrangeCoins(self, n: int) -> int:
        ans, level = 0, 1
        while ans < n:
            if ans + level <= n:
                ans += level
            else:
                break
            level += 1
        return level-1

原文地址:https://blog.csdn.net/mobius_strip/article/details/142892084

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!