Skip to content

904. Fruit Into Baskets 👍

  • Time:
  • Space:
 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) {
    int ans = 0;
    unordered_map<int, int> count;

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

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int totalFruit(int[] fruits) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (int l = 0, r = 0; r < fruits.length; ++r) {
      count.merge(fruits[r], 1, Integer::sum);
      while (count.size() > 2) {
        count.merge(fruits[l], -1, Integer::sum);
        count.remove(fruits[l], 0);
        ++l;
      }
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def totalFruit(self, fruits: list[int]) -> int:
    ans = 0
    count = collections.defaultdict(int)

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

    return ans