From 3b653401f7de7ccfc3433c5890ed54a627f93631 Mon Sep 17 00:00:00 2001 From: Aditya Pal Date: Tue, 10 Oct 2023 11:54:48 +0530 Subject: [PATCH 1/2] feat: Add leetcode problem 441 --- leetcode/src/441.c | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 leetcode/src/441.c diff --git a/leetcode/src/441.c b/leetcode/src/441.c new file mode 100644 index 0000000000..3407721229 --- /dev/null +++ b/leetcode/src/441.c @@ -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 - f 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 +} From 10c8873433871fc1c69dd9be798de1854c90a8d5 Mon Sep 17 00:00:00 2001 From: Aditya Pal Date: Tue, 10 Oct 2023 11:58:47 +0530 Subject: [PATCH 2/2] feat: Add leetcode problem 441 --- leetcode/src/441.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/leetcode/src/441.c b/leetcode/src/441.c index 3407721229..4c0df61727 100644 --- a/leetcode/src/441.c +++ b/leetcode/src/441.c @@ -13,7 +13,7 @@ int arrangeCoins(int n) long long int guess = mid * (mid + 1L) / 2; long long int prevGuess = (mid - 1L) * mid / 2; if (guess == n) - { // Edge case - f it's equal then the last row is full and we have + { // Edge case - if it's equal then the last row is full and we have // reached our answer return mid; }