forked from realpacific/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrangingCoins.kt
40 lines (35 loc) · 1.08 KB
/
ArrangingCoins.kt
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
package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* You have `n` coins and you want to build a staircase with these coins.
* The staircase consists of `k` rows where the `i`th row has exactly `i` coins.
* The last row of the staircase may be incomplete.
* Given the integer n, return the number of complete rows of the staircase you will build.
*
* [Source](https://leetcode.com/problems/arranging-coins/)
*/
@UseCommentAsDocumentation
private fun arrangeCoins(n: Int): Int {
if (n == 1) return 1
var temp = n
var col = 0
while (temp > 0) {
col++
temp -= col // load [col] number of coins on each column
}
var result = col
// [temp] is -ve if last column remains unfilled
// to fill this last column you can remove coins from last row and fill it
// this will decrease the number of complete rows by 1
if (temp < 0) {
result--
}
return result
}
fun main() {
arrangeCoins(2) shouldBe 1
arrangeCoins(1) shouldBe 1
arrangeCoins(5) shouldBe 2
arrangeCoins(8) shouldBe 3
}