forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
65 lines (53 loc) · 1.62 KB
/
main.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
53
54
55
56
57
58
59
60
61
62
63
64
65
/// Source : https://leetcode.com/problems/fruit-into-baskets/description/
/// Author : liuyubobobo
/// Time : 2018-09-15
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
/// Segment the array into blocks
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
int totalFruit(vector<int>& tree) {
vector<pair<int, int>> blocks;
int start = 0;
for(int i = start + 1; i <= tree.size(); i ++)
if(i == tree.size() || tree[i] != tree[start]){
blocks.push_back(make_pair(tree[start], i - start));
start = i;
i = start;
}
// for(const pair<int, int>& p: blocks)
// cout << "(" << p.first << "," << p.second << ") ";
// cout << endl;
int res = 0;
unordered_set<int> fruits;
int sum = 0;
for(int i = 0; i <= blocks.size();)
if(i == blocks.size() || (fruits.size() == 2 && fruits.count(blocks[i].first) == 0)){
res = max(res, sum);
if(i < blocks.size()){
sum = 0;
i --;
fruits.clear();
}
else
break;
}
else{
fruits.insert(blocks[i].first);
sum += blocks[i].second;
i ++;
}
return res;
}
};
int main() {
vector<int> nums1 = {1, 2, 1};
cout << Solution().totalFruit(nums1) << endl;
vector<int> nums2 = {0, 1, 2, 2};
cout << Solution().totalFruit(nums2) << endl;
return 0;
}