Created
October 4, 2019 23:41
-
-
Save OmarKRostom/fbc86f3624fe8cc99755ab72dcb34e79 to your computer and use it in GitHub Desktop.
Fruits into Basket (https://leetcode.com/problems/fruit-into-baskets/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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