-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fruits in a Basket.cpp
64 lines (48 loc) · 1.46 KB
/
Fruits in a Basket.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
//Brute Force
class Solution {
public:
int totalFruit(vector<int>& fruits) {
int i = 0 ;
int n = fruits.size();
int maxLen = 0 ;
while(i < n){
int j = i ;
int currLen = 0 ;
unorderd_set<int> distinct;
while(j < n && distinct.size() <= 2){
distinct.insert(fruits[j]);
if(distinct.size() <= 2){
//this is a valid subarray
currLen = j-i+1;
maxLen
}
}
}
}
};
//Optimised
#include <vector>
#include <unordered_map>
class Solution {
public:
int totalFruit(std::vector<int>& fruits) {
int n = fruits.size();
int maxLen = 0;
std::unordered_map<int, int> fruitLastIndex; // Map to store the last index of each fruit
int i = 0, j = 0;
while (j < n) {
fruitLastIndex[fruits[j]] = j;
if (fruitLastIndex.size() > 2) {
int minLastIndex = n;
for (const auto& entry : fruitLastIndex) {
minLastIndex = min(minLastIndex, entry.second);
}
i = minLastIndex + 1;
fruitLastIndex.erase(fruits[minLastIndex]);
}
maxLen = max(maxLen, j - i + 1);
++j;
}
return maxLen;
}
};