DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Fruit Into Baskets

var totalFruit = function (fruits) {
  let map = new Map();
  let max = 0;
  let tempArray = [];
  let end = 0;
  let array = fruits;
  let k = 2; // as total fruits is two you can have at a time


  while (array.length > end) {
    const nextChar = array[end];

    if (map.size < k && !map.has(nextChar)) {
      map.set(nextChar, 1);

      end++;
      tempArray.push(nextChar);
    } else if (map.size <= k && map.has(nextChar)) {
      map.set(nextChar, map.get(nextChar) + 1);

      end++;
      tempArray.push(nextChar);
    } else if (map.size === k && !map.has(nextChar)) {
      while (map.size === k) {
        // save the current
        if (tempArray.length > max) {
          max = tempArray.length;
        }

        let startValue = tempArray.shift();
        map.set(startValue, map.get(startValue) - 1);
        if (map.get(startValue) === 0) {
          map.delete(startValue);
        }
      }
    }
  }
  return max > tempArray.length ? max : tempArray.length;
};

console.log(totalFruit([1, 1, 1, 1, 1, 1, 1, 3, 2, 1]));
console.log(totalFruit([1, 2, 1], 2));
console.log(totalFruit([1, 2, 3, 2, 2]));
console.log(totalFruit([0, 1, 2, 2]));


Enter fullscreen mode Exit fullscreen mode

Top comments (0)