-
Notifications
You must be signed in to change notification settings - Fork 0
/
fruitIntoBaskets.kt
45 lines (37 loc) · 1.16 KB
/
fruitIntoBaskets.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
41
42
43
44
45
data class Basket(var type: Int, var size: Int)
fun totalFruit(fruits: IntArray): Int {
var firstType = fruits.firstOrNull() ?: return 0
val position = fruits.indexOfFirst { it != firstType }
if (position == -1) return fruits.size
var first = Basket(firstType, position)
var second = Basket(fruits[position], 1)
var last = second.copy()
var max = 0
fruits.asList().subList(position + 1, fruits.size).forEach {
when (it) {
first.type -> {
if (last.type == it) {
last.size++
} else {
last = Basket(it, 1)
}
first.size++
}
second.type -> {
if (last.type == it) {
last.size++
} else {
last = Basket(it, 1)
}
second.size++
}
else -> {
max = maxOf(max, first.size + second.size)
first = last
second = Basket(it, 1)
last = second.copy()
}
}
}
return maxOf(max, first.size + second.size)
}