-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfruitIntoBaskets.cpp
More file actions
45 lines (43 loc) · 934 Bytes
/
fruitIntoBaskets.cpp
File metadata and controls
45 lines (43 loc) · 934 Bytes
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
#include <iostream>
#include <vector>
#include <unordered_map>
// https://leetcode.com/problems/fruit-into-baskets/
class Solution
{
public:
int totalFruit(std::vector<int> &fruits)
{
int length = fruits.size();
int result = 0, tempRes = 0;
int i = 0;
std::unordered_map<int, int> tempMap;
while (i < length)
{
int curFruit = fruits[i];
if (tempMap.count(curFruit) == 0)
{
if (tempMap.size() < 2)
{
tempMap[curFruit] = 1;
tempRes += 1;
}
else
{
result = tempRes > result ? tempRes : result;
tempRes = 0;
int preFruit = fruits[i - 1];
i -= (tempMap[preFruit] + 1);
tempMap.clear();
}
}
else
{
tempMap[curFruit] += 1;
tempRes += 1;
}
i += 1;
}
result = tempRes > result ? tempRes : result;
return result;
}
};