Collect maximum fruits in two baskets of at most 2 types of fruits
Your second solution is good and fast, but you asked about more elegant solution, so I am suggesting mine. Firstly, I solved this task by Python, then convert all logic into Javascript. It is a little slower, than your (20 ms) and use more memory, but I think it more straightforward and understandable.

The code only answers do not liked on this site, so I add some comparisons:


Algorithm. Both algorithms are similar but:


Mine: keeps track of every number changing positions. The start1 position changes every time the number was changed, so I always know the position, where the previous number was started. The start2 position changes only when third number occurs, so I just subtract the start2 from the current index and get the needed two number sequence length.
Your: keeps track of last occurrences the first and second numbers, so you miss their start positions, and thus, you should use the count variable for storing the length of the current two number sequence. When the third number appears, you need to calculate the value of the last uninterruptible one number sequence by Math.abs(first - second). Also, you don't know which number was last - first or second, so the Math.abs function is needed.

The way of access to array items. 


Mine: uses the iterator - for...of statement and Array.entries(). It relieves us from tree[i] and tree[second] like constructions.
Your: Uses counter and array indexes to access the needed item.



The Javascript code:

var totalFruit = function(tree) {
    let n1 = -1;
    let n2 = -1;

    let start1 = 0;
    let start2 = 0;

    let maxim = 1;
    # Add extra element in the end of array (which is not occured in array)
    # to get rid of the second 'Math.max(maxim, k - start2)' call
    tree.push(-2);

    for (let [k, num] of tree.entries()) {
        if (num !== n1) {
            if (num !== n2) {
                maxim = Math.max(maxim, k - start2);
                start2 = start1;
            }

            n2 = n1;
            n1 = num;

            start1 = k;
        }
    }

    return maxim;
}


The original Python code:

class Solution:
    def totalFruit(self, tree):
        n1 = -1
        n2 = -1

        start1 = 0
        start2 = 0

        maxim = 1
        tree.append(-2)

        for k, num in enumerate(tree):
            if num != n1:
                if num != n2:
                    maxim = max(maxim, k - start2)

                    start2 = start1

                n2 = n1
                n1 = num

                start1 = k

        return maxim