forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
52 lines (42 loc) · 1.06 KB
/
main2.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/// Source : https://leetcode.com/problems/fruit-into-baskets/description/
/// Author : liuyubobobo
/// Time : 2018-09-15
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/// Sliding Window
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
int totalFruit(vector<int>& tree) {
unordered_map<int, int> freq;
int l = 0, r = -1, res = 0;
while(l < tree.size()){
if(freq.size() <= 2 && r + 1 < tree.size()){
r ++;
freq[tree[r]] ++;
}
else{
freq[tree[l]] --;
if(freq[tree[l]] == 0)
freq.erase(tree[l]);
l ++;
}
if(freq.size() <= 2)
res = max(res, getFruits(freq));
}
return res;
}
private:
int getFruits(const unordered_map<int, int>& freq){
int res = 0;
for(const pair<int, int>& p: freq)
res += p.second;
return res;
}
};
int main() {
return 0;
}