441. Arranging Coins
leetcode easy
#csharp#easy#leetcode#math
Task
У вас есть n монет, и вы хотите построить лестницу из этих монет. Лестница состоит из k рядов, где i-й ряд содержит ровно i монет. Последний ряд лестницы может быть неполным.
Дано целое число n, верните количество полных рядов лестницы, которые вы сможете построить.
Пример:
Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.
C# solution
matched/originalpublic class Solution {
public int ArrangeCoins(int n) {
return (int)(Math.Sqrt(2 * (long)n + 0.25) - 0.5);
}
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public int ArrangeCoins(int n) {
return (int)(Math.Sqrt(2 * (long)n + 0.25) - 0.5);
}
}Java solution
matched/originalclass Solution {
public int arrangeCoins(int n) {
return (int)(Math.sqrt(2 * (long)n + 0.25) - 0.5);
}
}JavaScript solution
matched/originalvar arrangeCoins = function(n) {
return Math.floor(Math.sqrt(2 * n + 0.25) - 0.5);
};Python solution
matched/originalclass Solution:
def arrangeCoins(self, n: int) -> int:
return int((2 * n + 0.25)**0.5 - 0.5)Go solution
matched/originalimport "math"
func arrangeCoins(n int) int {
return int(math.Sqrt(float64(2 * n) + 0.25) - 0.5)
}Explanation
Algorithm
Если мы глубже посмотрим на формулу задачи, мы можем решить её с помощью математики, без использования итераций.
Напомним, что условие задачи можно выразить следующим образом: k(k + 1) ≤ 2N.
Это можно решить методом выделения полного квадрата, (k + 1/2)² - 1/4 ≤ 2N. Что приводит к следующему ответу: k = [sqrt(2N + 1/4) - 1/2].
😎