904.水果成篮
链接:904.水果成篮
难度:Medium
标签:数组、哈希表、滑动窗口
简介:给你一个整数数组 fruits ,返回你可以收集的水果的 最大 数目。
题解 1 - cpp
- 编辑时间:2022-10-17
- 执行用时:204ms
- 内存消耗:69.4MB
- 编程语言:cpp
- 解法介绍:滑动窗口,每次记录窗口中小于 3 元素时的最大可能。
class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        unordered_map<int, int> m;
        int ans = 0, l = 0, r = 0, n = fruits.size();
        while (r < n) {
            m[fruits[r]]++;
            if (m.size() == 3) {
                do {
                    m[fruits[l]]--;
                    if (m[fruits[l]] == 0) m.erase(fruits[l]);
                    l++;
                } while (l < n && m.size() == 3);
            }
            ans = max(ans, r - l + 1);
            r++;
        }
        return ans;
    }
};