LeetCode 904. Fruit Into Baskets in Java

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.


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”

Sliding Window

I been reading, watching videos and experimenting with the Universal Windows Platform (UWP) and cpp/WinRT most of the day. On this final block I decided to take a break and make a post in my blog. I want to get some software done before the end of the day this Wednesday. Will let you know if I meet the deadline.

I noticed in my Gmail that JAVAAID had posted a video on YouTube titled “Sliding Windows Technique”. It called my attention because the Rabin-Karp algorithm is based on a sliding window technique.  In the past few months I wrote a post on the subject and named it “Rabin-Karp Algorithm” (not too creative on my part). Continue reading “Sliding Window”