Algorithm


Problem Name: 904. Fruit Into Baskets

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.

 

Example 1:

Input: fruits = [1,2,1]
Output: 3
Explanation: We can pick from all 3 trees.

Example 2:

Input: fruits = [0,1,2,2]
Output: 3
Explanation: We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].

Example 3:

Input: fruits = [1,2,3,2,2]
Output: 4
Explanation: We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].

 

Constraints:

  • 1 <= fruits.length <= 105
  • 0 <= fruits[i] < fruits.length

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


int totalFruit(int* tree, int treeSize){
    int i, j, f, l, m = 0;
    
    int cnt[40001] = { 0 };
    int k = 2;
    
    for (i = 0, j = 0; j  <  treeSize; j ++) {
        f = tree[j];
        if (cnt[f] == 0) k --;  // reached a new type of fruit tree
        cnt[f] ++;
        
        if (k == -1) {          // reached the 3rd type of fruit tree
            l = j - i;
            if (m  <  l) m = l;
            while (k == -1) {   // push out one type of fruit tree from head
                f = tree[i ++];
                cnt[f] --;
                if (cnt[f] == 0) k = 0;
            }
        }
    }
    
    l = j - i;
    if (m  <  l) m = l;
    
    return m;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
fruits = [1,2,1]

Output

x
+
cmd
3

#2 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    int totalFruit(vector<int>& tree) {
        int i = 0, j = 0, count = 0;
        unordered_map < int, int>m;
        int res = 0;
        while (j  <  tree.size()) {
            if (m[tree[j]] == 0) {
                ++count;
            }
            ++m[tree[j++]];
            while (count > 2) {
                if (--m[tree[i++]] == 0) {
                    --count;
                }
            }
            res = max(res, j - i);
        }
        return res;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
fruits = [1,2,1]

Output

x
+
cmd
3

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int totalFruit(int[] fruits) {
    Map map = new HashMap<>();
    int startIdx = 0;
    int endIdx = 0;
    int n = fruits.length;
    int maxPickedCount = 0;
    while (endIdx  <  n) {
      map.put(fruits[endIdx], map.getOrDefault(fruits[endIdx++], 0) + 1);
      while (startIdx < endIdx && map.size() > 2) {
        map.put(fruits[startIdx], map.get(fruits[startIdx]) - 1);
        if (map.get(fruits[startIdx]) == 0) {
          map.remove(fruits[startIdx]);
        }
        startIdx++;
      }
      maxPickedCount = Math.max(maxPickedCount, endIdx - startIdx);
    }
    return maxPickedCount;
  }   
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
fruits = [0,1,2,2]

Output

x
+
cmd
3

#4 Code Example with Javascript Programming

Code - Javascript Programming


const totalFruit = function (fruits) {
  let n = fruits.length
  let i = 0, j = 0
  const map = new Map()
  let res = 0
  for(;j  <  n; j++) {
    const e = fruits[j]
    if(!map.has(e)) map.set(e, 1)
    else map.set(e, map.get(e) + 1)

    while(map.size > 2 && i < n) {
      const tmp = fruits[i++]
      map.set(tmp, map.get(tmp) - 1)
      if(map.get(tmp) === 0) {
        map.delete(tmp)
      }
    }
    res = Math.max(res, j - i + 1>
  }

  return res
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
fruits = [0,1,2,2]

Output

x
+
cmd
3

#5 Code Example with Python Programming

Code - Python Programming


class Solution:
    def totalFruit(self, tree: List[int]) -> int:
        res = i = 0
        last = collections.defaultdict(int)
        for j, val in enumerate(tree):
            if len(last) == 2 and val not in last:
                pre = min(last.values())
                i = pre + 1
                last.pop(tree[pre])
            last[val] = j
            res = max(res, j - i + 1)
        return res
Copy The Code & Try With Live Editor

Input

x
+
cmd
fruits = [1,2,3,2,2]

Output

x
+
cmd
4

#6 Code Example with C# Programming

Code - C# Programming


using System;

namespace LeetCode
{
    public class _0904_FruitIntoBaskets
    {
        public int TotalFruit(int[] tree)
        {
            var b1 = -1;
            var b1Size = 0;
            var b2 = -1;
            var b2Size = 0;
            var max = 0;

            foreach (var treeType in tree)
            {
                if (b2 == -1)
                {
                    b2 = treeType;
                    b2Size = 1;
                }
                else if (b2 == treeType)
                {
                    b2Size++;
                }
                else if (b1 == treeType)
                {
                    b1 = b2;
                    b1Size += b2Size;
                    b2 = treeType;
                    b2Size = 1;
                }
                else
                {
                    b1 = b2;
                    b1Size = b2Size;
                    b2 = treeType;
                    b2Size = 1;
                }
                max = Math.Max(max, b1Size + b2Size);
            }
            return max;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
fruits = [1,2,3,2,2]

Output

x
+
cmd
4
Advertisements

Demonstration


Previous
#903 Leetcode Valid Permutations for DI Sequence Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#905 Leetcode Sort Array By Parity Solution in C, C++, Java, JavaScript, Python, C# Leetcode