Step-by-Step

[Java] Daily LeetCode Challenge 904. Fruit Into Baskets 본문

언어/JAVA

[Java] Daily LeetCode Challenge 904. Fruit Into Baskets

희주(KHJ) 2023. 2. 7. 21:08

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

백준은 유형별로 풀 수 있는 장점이 있지만,

하다 보면 점점 풀고 싶은 것만 풀고, 쉽게 다른 문제를 도전하지 않게 됐다.

 

격일로 릿코드 문제를 풀 예정 - 깃허브에 자동으로 올려주는 릿허브가 이제 사용이 거의 안돼서 아쉽긴 한데, 문제들이 좋아서 사용!

 

슬라이딩 윈도우 / 투포인터 사용하는 문제인데, 각자 푸는 방식으로 계산해주면 된다!

풀이가 긴 건 내가 실력이 부족해서이겠지..!? 통과하지 못한 테케를 보여주는데, 제출 전 테케 추가에 넣어주면 된다.

(이거 모르고 계속 제출했다가 오류만 산더미 ㅋㅋ)

 

[코드]

import java.util.*;
class Solution {
    public int totalFruit(int[] fruits) {
        HashMap<Integer, Integer> hm = new HashMap<>();
        HashSet<Integer> hs = new HashSet<>();

        int start = 0, end = 0, size = 0;
        for(end = 0; end <fruits.length; end++){
            int f = fruits[end];
            hm.put(f, hm.getOrDefault(f, 0));

            // 포함되어 있을 경우
            if(hm.getOrDefault(f,0)>0){
                hm.put(f, hm.get(f)+1);
            }else if(hs.size() < 2){  // 바구니가 안 찼을 경우
                hs.add(f);
                hm.put(f, 1);
            }else { // 바구니가 찼는데, 새로운 과일 발견
                size = Math.max(size, end - start);
                int[] nums = new int[2];
                int idx = 0;
                for(int a : hs)
                    nums[idx++] = a;

                while(hm.get(nums[0])!=0 && hm.get(nums[1])!=0){
                    int n = fruits[start++];
                    hm.put(n, hm.get(n)-1);
                }

                if(hm.get(nums[0])==0){
                    hs.remove(nums[0]);
                }else{
                    hs.remove(nums[1]);
                }
                hs.add(f);
                hm.put(f, 1);
            }
        }

        size = Math.max(size, end - start);
        return size;
    }
}

 

 

 

 

Comments