In this post we will solve the LeetCode 904. Fruit Into Baskets problem using the Java programming language.
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: o You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold. o Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. o Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array fruits, return the maximum number of fruits you can pick. Constraints: o 1 <= fruits.length <= 10^5 o 0 <= fruits[i] < fruits.length Related Topics: o Array o Hash Table o Sliding Window
The two approaches that came to mind are using a hashmap, which should not have the best performance but should be acceptable, and the second using a sliding window, which should be faster than the one using a hashmap. Continue reading “LeetCode 904. Fruit Into Baskets in Java”