Skip to content

Instantly share code, notes, and snippets.

@OmarKRostom
Created October 4, 2019 23:41
Show Gist options
  • Save OmarKRostom/fbc86f3624fe8cc99755ab72dcb34e79 to your computer and use it in GitHub Desktop.
Save OmarKRostom/fbc86f3624fe8cc99755ab72dcb34e79 to your computer and use it in GitHub Desktop.
fun totalFruit(tree: IntArray): Int {
val collectedFruitSet = ArrayList<Int>()
var lastMax = 0
for (loopingIndex in 0 until tree.size) {
if (tree.distinct().count() <= 2) {
lastMax = tree.size
break
} else if (collectedFruitSet.distinct().count() < 2 || (
collectedFruitSet.distinct().count() == 2 && collectedFruitSet.contains(tree[loopingIndex])
)
) {
collectedFruitSet.add(tree[loopingIndex])
} else {
var tempIndex = 0
while (collectedFruitSet.distinct().count() > 1) {
if (!collectedFruitSet.contains(tree[loopingIndex])) collectedFruitSet.removeAt(0)
else break
tempIndex++
}
collectedFruitSet.add(tree[loopingIndex])
}
lastMax = max(lastMax, collectedFruitSet.size)
}
return lastMax
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment