forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrangingCoins.java
41 lines (34 loc) · 866 Bytes
/
ArrangingCoins.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class ArrangingCoins {
public static void main(String[] args) {
int n = 1;
System.out.println(arrangeCoins2(n));
}
static int arrangeCoins(int n) {
long s = 1;
long e = n;
while(s <= e){
long m = s + (e-s)/2;
long coinsNeeded = (m * (m+1)) /2;
if(coinsNeeded <= n){
s = m+1;
} else{
e= m-1;
}
}
return (int)e;
}
static int arrangeCoins2(int n){
long s = 1;
long e = n;
while(s < e){
long m = s + (e-s)/2;
long coinsNeeded = (m * (m+1)) /2;
if(coinsNeeded <= n){
s = m+1;
} else{
e = m;
}
}
return (s * (s+1)) /2 <= n ? (int)s : (int)s-1;
}
}