-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrangeCoins.java
More file actions
52 lines (37 loc) · 843 Bytes
/
ArrangeCoins.java
File metadata and controls
52 lines (37 loc) · 843 Bytes
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
42
43
44
45
46
47
48
49
50
51
52
package com.vinay.practice.lc;
// https://leetcode.com/problems/arranging-coins/description/
public class ArrangeCoins {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(arrangeCoins(8));
}
public static int arrangeCoins(int n) {
/*
// O(n)
long temp = 0, i=0;
while(temp < n){
i=i+1;
temp = temp + i;
}
if((temp - n) == 0){
return (int)i;
} else{
return (int)--i;
}
*/
long start = 1;
long end = n;
while(start <= end) {
long mid = start + (end-start)/2;
long currSum = mid * (mid + 1) / 2;
if(currSum == n)
return (int)mid;
if(currSum > n) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return (int)end;
}
}