Problem 904

Abstract / Summary

You must pick as much fruit as possible from trees while only collecting from at most two types of trees at a time.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0904.py

class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        if len(fruits) <= 2:
            return len(fruits)

        result = streak = 2 # always possible to pick from the first two trees
        a      = fruits[0]
        b      = fruits[1]
        prev   = b
        repeat = 1
        for f in fruits[2:]:
            if f == a or f == b or a == b:
                # keep picking
                streak += 1
                if a == b:
                    a = f
            else:
                # start new streak
                result = max(result, streak)
                streak = 1 + repeat # first two trees of every streak are valid
                a = prev
                b = f

            if prev == f:
                repeat += 1
            else:
                prev   = f
                repeat = 1

        return max(result, streak) # maybe best streak ended on the final tree
30 lines | 946 bytes | submitted October 24, 2023 | GitHub   20% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “fruit into baskets” problem: given a list of fruit types represented by integers, determine the length of the longest contiguous sub-array that contains at most two distinct fruit types. The algorithm walks through the list once, maintaining a sliding window that respects the two-type constraint while tracking the longest window encountered.

Key Steps

Initial Guard Clause

if len(fruits) <= 2:
    return len(fruits)

When the input contains two or fewer elements, the whole array trivially satisfies the constraint, so the function returns its length immediately. This early exit prevents unnecessary processing for trivial cases.

Variable Initialization

result = streak = 2  # always possible to pick from the first two trees
a = fruits[0]
b = fruits[1]
prev = b
repeat = 1

result stores the best length found so far, while streak tracks the length of the current valid window. The variables a and b hold the two fruit types currently allowed in the window. prev remembers the fruit type of the immediate predecessor, and repeat counts how many consecutive occurrences of prev have been seen. Initializing result and streak to 2 reflects the guarantee that the first two trees can always be included.

Main Loop Over Remaining Fruits

for f in fruits[2:]:
    if f == a or f == b or a == b:
        # keep picking
        streak += 1
        if a == b:
            a = f
    else:
        # start new streak
        result = max(result, streak)
        streak = 1 + repeat  # first two trees of every streak are valid
        a = prev
        b = f

For each fruit f beyond the first two, the algorithm checks whether f matches one of the two allowed types (a or b) or whether the two allowed types are currently identical (a == b). If the condition holds, the current window can be extended (streak += 1). When both allowed types are the same, the new fruit type becomes the second distinct type (a = f).

If f introduces a third distinct type, the current window ends. The best length is updated (result = max(result, streak)). A new window starts with the last contiguous block of the previous fruit type (repeat counts) plus the new fruit, giving streak = 1 + repeat. The allowed types are refreshed: a becomes the previous fruit (prev), and b becomes the new fruit f.

Updating Consecutive Count

if prev == f:
    repeat += 1
else:
    prev = f
    repeat = 1

After handling the inclusion or reset logic, the algorithm updates the consecutive count. When the current fruit matches the previous one, the repeat counter increments, preserving the length of the trailing block of identical fruits. When a different fruit appears, prev is set to the new fruit and repeat resets to 1. This information is crucial for correctly initializing the next window after a type violation.

Final Result Computation

return max(result, streak)  # maybe best streak ended on the final tree

The loop may finish while the longest window is still active. The final max ensures that a streak ending at the last element is considered.

Edge Cases Handled

The algorithm explicitly addresses several boundary conditions:

  • Input lists of length 0, 1, or 2 are resolved by the early guard clause, returning the exact length.
  • When the first two fruits are identical (a == b), the code treats them as a single type until a different fruit appears, correctly expanding the allowed set.
  • Consecutive runs of the same fruit type are tracked via repeat. This enables the algorithm to start a new window that includes the entire trailing block of the previous fruit when a third type appears.
  • The final max call captures scenarios where the longest valid sub-array extends to the end of the list, preventing loss of the last streak.

Performance Optimizations

The solution achieves linear traversal by maintaining only a constant set of scalar variables (result, streak, a, b, prev, repeat). No auxiliary data structures such as dictionaries or sets are allocated, which eliminates overhead associated with dynamic resizing or hashing. The conditional checks are arranged to short-circuit quickly: the most common path (continuing the current window) executes a simple increment, while the reset path performs a few assignments and a max operation. By reusing the repeat counter instead of recomputing the length of the trailing block, the algorithm avoids a secondary scan, preserving the single-pass nature of the computation. The early return for short inputs prevents unnecessary loop entry, further reducing runtime for trivial cases.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of fruit trees stretching out as far as the eye can see. Each tree has a different kind of fruit hanging from its branches. Walking along this path, there is a basket that can hold fruit from only two different types of trees at a time. The goal is to walk down the row and gather as much fruit as possible without picking a third kind.

At the very start, the code looks at the first two trees and assumes they are the two types allowed in the basket. It keeps track of how many fruits are collected in a row, which is called a streak. When moving to the next tree, the code checks if the fruit on that tree is one of the two types already inside the basket. If it is, the fruit is added to the count and the streak keeps growing.

Sometimes, a third type of fruit appears, which means the basket is full and a new section must begin. When this happens, the code remembers the biggest pile of fruit gathered so far and starts a fresh count. It looks back at the fruit right before the new one to decide which two types will be kept for the next part of the trip. The code also keeps a close eye on the last few trees to see if there is a long line of the same fruit, as those are very easy to collect. By the time the end of the row is reached, the highest number of fruits collected during any part of the walk is revealed.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.11 | σ = 1.37

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java C++ Python TS
WalkCCC Java C++ Python
leetcode.ca Java C++ C# Python Rust Go TS
LeetcodeHelp Java C++ Python
Progiez Java C++ Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
fpdjsns C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
lkwq007 Python
MacJim C++
qiyuangong Java
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
fpdjsns C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
MacJim C++
qiyuangong Java
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
39 links | 24 authors | 9 languages

Videos

10 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

1 easy 7 medium 1 hard
10 solutions   October 24, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality