Skip to content

Instantly share code, notes, and snippets.

@NAVNEETOJHA
Created July 2, 2020 07:08
Show Gist options
  • Save NAVNEETOJHA/6e855a2c28b866a009a8cd3af6a20d5e to your computer and use it in GitHub Desktop.
Save NAVNEETOJHA/6e855a2c28b866a009a8cd3af6a20d5e to your computer and use it in GitHub Desktop.
// You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
// Given n, find the total number of full staircase rows that can be formed.
// n is a non-negative integer and fits within the range of a 32-bit signed integer.
// Example 1:
// n = 5
// The coins can form the following rows:
// ¤
// ¤ ¤
// ¤ ¤
// Because the 3rd row is incomplete, we return 2.
class Solution {
public int arrangeCoins(int n) {
int low = 1, high = n, mid;
while (low <= high) {
//find mid
mid = low + (high - low) / 2;
//n*(n+1)/2 <= n
if (mid * (mid + 1) <= n * 2)
low = mid + 1;
else high = mid - 1;
}
return high;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment