Skip to content

Instantly share code, notes, and snippets.

@JyotinderSingh
Created July 1, 2020 09:28
Show Gist options
  • Save JyotinderSingh/59175e7356f7ac7ae4e634c23c37d734 to your computer and use it in GitHub Desktop.
Save JyotinderSingh/59175e7356f7ac7ae4e634c23c37d734 to your computer and use it in GitHub Desktop.
Arranging Coins (LeetCode) | Binary Search Algorithm Explanation
class Solution {
public:
int arrangeCoins(int n) {
long n_long = (long) n;
long left = 1, right = n_long;
while(left <= right) {
long mid = left + (right - left) / 2; // (left + right) / 2
if(mid * (mid + 1) / 2 <= n_long) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return (int) left - 1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment