[LeetCode] Fruit Into Baskets

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
int totalFruit(vector<int>& fruits) {
int l = 0, r = 0, n = fruits.size(), res = 0;
pair<int, int> pick1{-1,0}, pick2{-1, 0}; //fruit type, fruit count
while(r < n) {
//move left if new fruit;
while(pick1.second and pick2.second and !(pick1.first == fruits[r] or pick2.first == fruits[r])) {
if(pick1.first == fruits[l]) pick1.second--;
else pick2.second--;
l++;
}

//plus fruit;
if(pick1.first == fruits[r]) pick1.second++;
else if(pick2.first == fruits[r]) pick2.second++;
else if(pick1.second == 0) pick1 = {fruits[r],1};
else pick2 = {fruits[r],1};

//distance
res = max(res, r - l + 1);

//move right
r++;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/15/PS/LeetCode/fruit-into-baskets/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.