Approach 1: Based on binary search and inequalities
The time complexity is super-fast: O(lg n) where n is the the input N(the number of coins) and I don't think it can get any faster iteratively.
class Solution {
public int arrangeCoins(int N) {
long minLevel = 0;
long maxLevel = N;
while (minLevel<maxLevel) {
long midLevel = minLevel + (maxLevel-minLevel+1)/2;
boolean predicate = ((midLevel*midLevel + midLevel) > (2*(long)N));
if (predicate) {
maxLevel = midLevel-1;
}
else {
minLevel = midLevel;
}
}
if ((minLevel*minLevel + minLevel) > (2*(long)N))
return -1;
return (int)minLevel;
}
}The time complexity is super-fast: O(lg n) where n is the the input N(the number of coins) and I don't think it can get any faster iteratively.
The only other faster solution I can think of is using SriDharacharya formula to find the roots to inequality:
l^2 + l <= 2*N
where l = last complete level
Do share your thoughts below!
<3
~Take Care
~Take Care
No comments:
Post a Comment