Medium
,Array
,Hash Table
,Sliding Window
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:
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:
fruits.length
<= 105fruits[i]
< fruits.length
class Solution {
public:
int totalFruit(vector<int>& fruits) {
int ans = 0, i = 0;
unordered_map<int, int> counter;
for (int j = 0; j < fruits.size(); j++) {
counter[fruits[j]] += 1;
while (counter.size() > 2) {
counter[fruits[i]] -= 1;
if (counter[fruits[i]] == 0) counter.erase(fruits[i]);
i++;
}
ans = max(ans, j - i + 1);
}
return ans;
}
};
Yen-Chi ChenTue, Feb 7, 2023
class Solution {
public:
int totalFruit(vector<int>& fruits) {
unordered_set<int> s;
int prev_start_index = 0, res = 1, cur_length = 1;
s.insert(fruits[0]);
for(int i = 1; i < fruits.size(); i++)
{
if(fruits[i] == fruits[i-1])
cur_length++;
else
{
if(s.size() < 2)
s.insert(fruits[i]);
else
{
if(!s.count(fruits[i]))
{
cur_length = i - prev_start_index;
int too_far_n = -1;
for(auto n : s)
{
if(n != fruits[i-1])
too_far_n = n;
}
s.erase(too_far_n);
s.insert(fruits[i]);
}
}
cur_length++;
prev_start_index = i;
}
res = max(res, cur_length);
}
return res;
}
};
Time:
Extra Space:
XD Feb 7, 2023
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
ans, l = 0, 0
cnt = Counter()
for r, fruit in enumerate(fruits):
cnt[fruit] += 1
while len(cnt) > 2:
cnt[fruits[l]] -= 1
if cnt[fruits[l]] == 0:
del cnt[fruits[l]]
l += 1
ans = max(ans, r - l + 1)
return ans
Yen-Chi ChenTue, Feb 7, 2023
function totalFruit(fruits) {
let left = 0;
let max = 0;
let count = 0;
const baskets = [];
for (let i = 0; i < fruits.length; i++) {
if (baskets.includes(fruits[i])) {
count++;
} else {
if (baskets.length < 2) {
baskets.push(fruits[i]);
count++;
} else {
// 往前找到第一個不同的水果
for (let j = i - 1; j >= left; j--) {
if (fruits[j] !== fruits[i - 1]) {
left = j + 1; // 更新起始點
break;
}
}
// 重新裝水果
baskets[0] = fruits[i - 1];
baskets[1] = fruits[i];
count = i - left + 1;
}
}
max = Math.max(max, count);
}
return max;
}
參考前面兩位大神的解法寫出來了,感恩兩位大神!
MarsgoatFeb 9, 2023