Home Leetcode 904 - Fruit Into Baskets
Post
Cancel

Leetcode 904 - Fruit Into Baskets

Link to problem

Description

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:

  • 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.
  • 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.
  • 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.

Solution

For this problem, we are finding the max length of a subarray that has only two different numbers in it.

This could be solved by using a sliding window and a hash map for recording the numbers and its count in this subarray.

Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        unordered_map<int, int> count;
        int front = 0, back = 0;
        int maxCount = 0;

        for (; back < fruits.size(); back++) {
            count[fruits[back]]++;
            while (count.size() > 2) {
                if (--count[fruits[front]] == 0) count.erase(fruits[front]);
                front++;
            }
            maxCount = max(maxCount, back - front + 1);
        }

        return maxCount;
    }
};

A more cool way of doing this is to keep the maximum length of the sliding window (therefore, front and back pointers). And keep processing numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        unordered_map<int, int> count;
        int front = 0, back = 0;

        for (; back < fruits.size(); back++) {
            count[fruits[back]]++;
            if (count.size() > 2) {
                if (--count[fruits[front]] == 0) count.erase(fruits[front]);
                front++;
            }
        }

        return back - front;
    }
};
This post is licensed under CC BY 4.0 by the author.