๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 904 - Fruit Into Baskets (Medium)

by HandHand 2021. 3. 8.

๋ฌธ์ œ

LeetCode - 904๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ตœ๋Œ€ 2์ข…๋ฅ˜์˜ ๊ณผ์ผ์„ ๋‹ด์„ ์ˆ˜ ์žˆ๋Š” ๋ฐ”๊ตฌ๋‹ˆ๋ฅผ ์ด์šฉํ•ด์„œ ๊ฐ€๋Šฅํ•œ ๋งŽ์€ ๊ณผ์ผ์„ ๋‹ด์€ ๊ฒฝ์šฐ๋ฅผ ์ฐพ๋Š” ํˆฌ ํฌ์ธํ„ฐ ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

head ์™€ tail ์„ ์ด์šฉํ•ด์„œ ๊ณผ์ผ์„ ํ•˜๋‚˜์”ฉ ์ˆœํšŒํ•˜๋Š”๋ฐ, 2์ข…๋ฅ˜์˜ ์ œ์•ฝ์กฐ๊ฑด์„ ๋งŒ์กฑ์‹œํ‚ค๋Š” ๊ณผ์ผ์ด๋ฉด tail ์„ ์ฆ๊ฐ€์‹œํ‚ค๊ณ 
๊ทธ๋ ‡์ง€ ์•Š์„ ๊ฒฝ์šฐ ์ด๋ฅผ ๋งŒ์กฑํ• ๋•Œ๊นŒ์ง€ head ๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•์„ ์ด์šฉํ•ด์„œ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} tree
 * @return {number}
 */
var totalFruit = function (tree) {
  let head = 0;
  let tail = 0;
  let answer = 1;
  const basket = new Map();

  basket.set(tree[head], 1);

  while (head <= tail) {
    tail += 1;
    if (tail >= tree.length) {
      break;
    }

    const fruit = tree[tail];
    basket.set(fruit, basket.get(fruit) + 1 || 1);

    // if overload
    while (basket.size > 2) {
      const fruit = tree[head];

      basket.set(fruit, basket.get(fruit) - 1);
      if (basket.get(fruit) === 0) {
        basket.delete(fruit);
      }

      head += 1;
    }

    answer = Math.max(answer, tail - head + 1);
  }

  return answer;
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€