**Task**

is from LeetCode

In a row of trees, the i-th tree produces fruits of type `tree[i]`

.

You start at the tree of your choice, and then make several times the

Following steps:

- Add a fruit from this tree to your baskets. If you can not, stop.
- Go to the next tree, to the right of the current tree. If there is no tree on the right, stop.

Note that you have no choice after the initial choice of

starting tree: you must execute step 1, then step 2, then go back to step

1, then step 2 and so on until you stop.

You have two baskets, and each basket can contain any amount of fruit,

but you want each basket to only carry one type of fruit. What is

the total amount of fruit that you can collect with this procedure?

**Example 1**

```
Contribution: [1,2,1]
Released: 3
// Explanation: We can collect [1,2,1].
```

**Example 2**

```
Contribution: [0,1,2,2]
Released: 3
// Explanation: We can collect [1,2,2].
// If we started at the first tree, we would only collect [0, 1].
```

**Example 3**

```
Contribution: [1,2,3,2,2]
Released: 4
// Explanation: We can collect [2,3,2,2].
// If we started at the first tree, we would only collect [1, 2].
```

**Example 4**

```
Contribution: [3,3,3,1,2,1,1,2,3,3,4]
Released: 5
// Explanation: We can collect [1,2,1,1,2].
// If we start from the first or the eighth tree, we would only harvest four fruits.
```

**Note:**

- 1 <= tree.length <= 40000
- 0 <= tree[i] <tree.length

**My solution:**

has the complexity of time and space of *Sure)*. At first, I thought it was easy. But then, I got mixed up with the one of the test cases (i.e. `I = [3,3,3,1,2,1,1,2,3,3,4];`

) and everything inside the `other`

-block is a bit hacky after. Perhaps there is a more elegant solution to that.

```
/ **
* @param {number[]} tree
* @return {number}
* /
var totalFruit = function (tree) {
const set = new Set (tree);
if (set.size <= 2) {
return tree.length;
}
const fruits = new Set ();
let i = 0;
let j = 0;
leave max = 0;
let count = 0;
while (j <tree.length) {
if (fruits.size <= 2 &&! fruits.has (tree[j])) {
fruits.add (tree[j])
}
if (fruits.size <= 2) {
count ++;
max = Math.max (max, count);
j ++;
} other {
fruits.delete (tree[i])
const lastIndex = tree.slice (i, j - 1) .lastIndexOf (tree[i])
i + = lastIndex + 1;
count- = lastIndex + 1;
}
}
back max;
};
leave me = [1,2,1];
I = [0,1,2,2];
I = [3,3,3,1,2,1,1,2,3,3,4];
console.log (totalFruit (I));
```