LeetCode Solutions

904. Fruit Into Baskets

Time:

Space:

			

class Solution {
 public:
  int totalFruit(vector<int>& tree) {
    int ans = 0;
    unordered_map<int, int> count;

    for (int l = 0, r = 0; r < tree.size(); ++r) {
      ++count[tree[r]];
      while (count.size() > 2) {
        if (--count[tree[l]] == 0)
          count.erase(tree[l]);
        ++l;
      }
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
			

class Solution {
  public int totalFruit(int[] tree) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (int l = 0, r = 0; r < tree.length; ++r) {
      count.put(tree[r], count.getOrDefault(tree[r], 0) + 1);
      while (count.size() > 2) {
        count.put(tree[l], count.get(tree[l]) - 1);
        count.remove(tree[l], 0);
        ++l;
      }
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
			

class Solution:
  def totalFruit(self, tree: List[int]) -> int:
    ans = 0
    count = defaultdict(int)

    l = 0
    for r, t in enumerate(tree):
      count[t] += 1
      while len(count) > 2:
        count[tree[l]] -= 1
        if count[tree[l]] == 0:
          del count[tree[l]]
        l += 1
      ans = max(ans, r - l + 1)

    return ans