Skip to content

Commit 208592d

Browse files
author
Partho Biswas
committed
441. Arranging Coins
1 parent a05efd6 commit 208592d

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,7 @@ I have solved quite a number of problems from several topics. See the below tabl
384384
|31| **[1231. Divide Chocolate](https://tinyurl.com/rduxzj3)** | [Python](https://tinyurl.com/wu6rdaw/1231_Divide_Chocolate.py), [Swift](https://tinyurl.com/wuja3c4/1231_Divide_Chocolate.swift) | [Art 1](https://tinyurl.com/sl7w7cb), [Art 2](https://tinyurl.com/w9wbcyl), [Art 3](https://tinyurl.com/te6wq5e) | Hard | I loved this problem. Very important |
385385
|32| **[1268. Search Suggestions System](https://tinyurl.com/ybwcd5nx)** | [Python](https://tinyurl.com/wu6rdaw/1268_Search_Suggestions_System.py), [Swift](https://tinyurl.com/wuja3c4/1268_Search_Suggestions_System.swift) | [Art 1](https://tinyurl.com/yac3kvrp), [Art 2](https://tinyurl.com/y9u3g66q), [Art 3](https://tinyurl.com/yc2u3mrx) | Medium | I loved this problem. Very versatile, ca be solved in a lot of different ways |
386386
|33| **[540. Single Element in a Sorted Array](https://tinyurl.com/y78xdorh)** | [Python](https://tinyurl.com/wu6rdaw/540_Single_Element_in_a_Sorted_Array.py), [Swift](https://tinyurl.com/wuja3c4/1268_Search_Suggestions_System.swift) | | Medium | --- |
387+
|34| **[441. Arranging Coins](https://tinyurl.com/yaj6labj)** | [Python](https://tinyurl.com/wu6rdaw/441_Arranging_Coins.py), [Swift](https://tinyurl.com/wuja3c4/441_Arranging_Coins.swift) | | Easy | --- |
387388

388389

389390
</p>
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import Foundation
2+
3+
// Brute force solution. Time Limit Exceeded
4+
class Solution {
5+
func arrangeCoins(_ n: Int) -> Int {
6+
if n == 0 {
7+
return 0
8+
}
9+
10+
var (coins, steps) = (0, 0)
11+
for i in 1...n {
12+
coins += i
13+
if coins <= n {
14+
steps += 1
15+
}
16+
}
17+
return steps
18+
}
19+
}
20+
21+
22+
// Binary Search
23+
import Foundation
24+
class Solution {
25+
func arrangeCoins(_ n: Int) -> Int {
26+
var (left, right) = (0, n)
27+
while left <= right {
28+
var mid: Int = (left + right)/2
29+
var requiredCoing = (mid*(mid + 1)) / 2
30+
if requiredCoing == n {
31+
return mid
32+
}
33+
if requiredCoing > n {
34+
right = mid - 1
35+
} else {
36+
left = mid + 1
37+
}
38+
}
39+
return right
40+
}
41+
}
42+
43+
/*
44+
logn
45+
46+
1-1
47+
2-3
48+
3-6
49+
4-10
50+
5-15
51+
6-21
52+
7-28
53+
8-36
54+
9-45
55+
1+2+3+4+5+6 = k(k+1)/2
56+
57+
*/

0 commit comments

Comments
 (0)