Skip to content

Commit 6f9e95b

Browse files
committed
Arranging coins.
1 parent 97007b8 commit 6f9e95b

File tree

4 files changed

+44
-0
lines changed

4 files changed

+44
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.
3+
4+
Given the integer n, return the number of complete rows of the staircase you will build.
5+
6+
 
7+
8+
Example 1:
9+
Input: n = 5
10+
Output: 2
11+
Explanation: Because the 3rd row is incomplete, we return 2.
12+
13+
Example 2:
14+
Input: n = 8
15+
Output: 3
16+
Explanation: Because the 4th row is incomplete, we return 3.
17+
*/
18+
class Solution {
19+
func arrangeCoins(_ n: Int) -> Int {
20+
if n == 1 || n == 2 { return 1 }
21+
if n == 3 { return 2 }
22+
var k = 3
23+
while (n - k * (k - 1) / 2 > 0) && (n - k * (k - 1) / 2 > k) {
24+
k += 1
25+
}
26+
return n - k * (k - 1) / 2 == k ? k : k - 1
27+
}
28+
}
29+
30+
let s = Solution()
31+
let r = s.arrangeCoins(3)
32+
print(r)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/441.Arranging Coins.playground/playground.xcworkspace/contents.xcworkspacedata

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@
8888
84. [Third Maximum Number](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/414.Third%20Maximum%20Number.playground/Contents.swift)
8989
85. [Add Strings](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/415.Add%20Strings.playground/Contents.swift)
9090
86. [Number of Segments in a String](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/434.Number%20of%20Segments%20in%20a%20String.playground/Contents.swift)
91+
87. [Arranging Coins](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/441.Arranging%20Coins.playground/Contents.swift)
9192

9293
#### Medium
9394

0 commit comments

Comments
 (0)