# Leetcode 904. Fruit Into Baskets ###### tags: `leetcode` `daily` `Sliding window` `two pointer` [題目連結](https://leetcode.com/problems/fruit-into-baskets/description/) # Method Sliding Window :::info :bulb: **作法講解**: step 1, we are maintaing window, initially size is 1, that means start=0, end=0 we using hash_map to record each element in current window at fruits. step 2, scan each index end in fruits, increment the count of hash_map with key is fruit[end], when hash_map size is over than 2, we move start to the next element, in the meantime, decrement the count of hash_map with key is fruit[start]. candidate of output is length between start to end ::: TC: O(N) SC: O(1) :::spoiler 完整程式碼 ```cpp= class Solution { public: int totalFruit(vector<int>& fruits) { int n = fruits.size(); int l = 0; int output = 0; unordered_map<int, int> m; for(int i = 0 ; i < n ; i++) { m[fruits[i]]++; while(m.size() > 2) { m[fruits[l]]--; if(m[fruits[l]] == 0) { m.erase(fruits[l]); } l++; } output = max(output, i - l + 1); } return output; } }; ``` :::