Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add leetcode problem 441 #1344

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions leetcode/src/441.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Given n coins, find out how many rows can be filled with them if each row has
// one more coin than the last (starting from 1 coin. Last row may or may not be
// full)
int arrangeCoins(int n)
{
// We need to find the point where n(n + 1) / 2 is just bigger than input -
// that minus 1 is our answer, since the sum will be that number. So we will
// use binarySearch for it
int low = 1, high = 10e5; // 10e5 square is bigger than constraints
while (low <= high)
{
int mid = (low + high) / 2;
long long int guess = mid * (mid + 1L) / 2;
long long int prevGuess = (mid - 1L) * mid / 2;
if (guess == n)
{ // Edge case - if it's equal then the last row is full and we have
// reached our answer
return mid;
}
else if (guess > n && prevGuess < n)
{
return mid - 1;
}
else if (guess > n)
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return -1; // Return -1 to satisfy the compiler although early exit via
// `return` is guaranteed by problem constraints
}
Loading