파비의 매일매일 공부기록

2023.02.07 Today's Challenge 본문

Problem Solving/LeetCode

2023.02.07 Today's Challenge

fabichoi 2023. 2. 7. 23:45

https://leetcode.com/problems/fruit-into-baskets/

 

Fruit Into Baskets - LeetCode

Fruit Into Baskets - You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces. You want to collect as much frui

leetcode.com

슬라이딩 윈도우 기법이 생각보다 많이 쓰이네 -_-;

class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        basket = {}
        max_picked = 0
        left = 0

        for right in range(len(fruits)):
            basket[fruits[right]] = basket.get(fruits[right], 0) + 1

            while len(basket) > 2:
                basket[fruits[left]] -= 1
                if basket[fruits[left]] == 0:
                    del basket[fruits[left]]
                left += 1

            max_picked = max(max_picked, right-left+1)
        
        return max_picked
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.02.09 Today's Challenge  (0) 2023.02.09
2023.02.08 Today's Challenge  (0) 2023.02.08
2023.02.06 Today's Challenge  (0) 2023.02.06
2023.02.05 Today's Challenge  (0) 2023.02.05
2023.02.04 Today's Challenge  (0) 2023.02.04
Comments