Skip to content

Commit

Permalink
Create fruit-into-baskets.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Sep 16, 2018
1 parent 2eff7e0 commit 0a93b4b
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions C++/fruit-into-baskets.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Time: O(n)
// Space: O(1)

class Solution {
public:
int totalFruit(vector<int>& tree) {
unordered_map<int, int> count;
int result = 0, i = 0;
for (int j = 0; j < tree.size(); ++j) {
++count[tree[j]];
while (count.size() > 2) {
--count[tree[i]];
if (count[tree[i]] == 0) {
count.erase(tree[i]);
}
++i;
}
result = max(result, j - i + 1);
}
return result;
}
};

0 comments on commit 0a93b4b

Please sign in to comment.