You have (n) coins, and you want to build a staircase with them. The staircase consists of (k) rows where the (i)-th row has exactly (i) coins. The last row of the staircase may be incomplete if there are not enough coins.
Given the integer (n), return the number of complete rows of the staircase you will be able to form.
We need to find the maximum number of complete rows that can be formed with the given number of coins, (n). This problem can be solved using a mathematical approach by recognizing the sequence of rows:
#include <iostream>
using namespace std;
class Solution {
public:
int arrangeCoins(int n) {
long left = 0, right = n; // using long to handle large values
while (left <= right) {
long mid = left + (right - left) / 2;
long curr = mid * (mid + 1) / 2;
if (curr == n) {
return mid;
} else if (curr < n) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return right; // When left > right, right is the largest k such that k*(k+1)/2 <= n
}
};
int main() {
Solution solution;
int n;
cout << "Enter the number of coins: ";
cin >> n;
cout << "Number of complete rows: " << solution.arrangeCoins(n) << endl;
return 0;
}
The time complexity of the above solution is (O(\log n)) because we are using binary search to determine the maximum number of complete rows. The space complexity is (O(1)) as we are using a constant amount of extra space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?