coding test

[파이썬, Java] 쿠키 구입

잔망루피 2023. 4. 12. 20:29
반응형

🟨 나의 풀이

class Solution {
    
    public int solution(int[] cookie) {
        int answer = 0;
        
        for(int i=0; i < cookie.length-1; i++){
            int left = i;
            int right = i + 1;
            int left_total = cookie[i];
            int right_total = cookie[i + 1];
            
            while (true) {
                if (left_total == right_total) {
                    answer = Math.max(answer, left_total);
                }
                if (left_total >= right_total && right < cookie.length - 1) {
                    right += 1;
                    right_total += cookie[right];
                }else if(left_total < right_total && left > 0) {
                    left -= 1;
                    left_total += cookie[left];
                }else{
                    break;
                }
            }
        }
        
        return answer;
    }
}

기준점은 0 ~ cookie의 개수 -1까지다.

인덱스 범위 안에서 전체를 탐색한다.

쿠키가 더 작은 쪽에 쿠키를 준다.

⚠️ 주의할 점

  • if (left_total > right_total && right < cookie.length - 1)로 하면 안 된다.
    • 만약 초기 left_total과 right_total이 같으면, if (left_total == right_total)이 실행된 후 break하고 끝난다.
    • 배열 전체를 탐색해야 한다 !!!

 

# 실패
def solution(cookie):
    answer = -1
    len_cookie = len(cookie)

    for i in range(len_cookie - 1):
        left_idx = i
        right_idx = i + 1
        left = 0
        right = 0
        while True:
            if left_idx < 0 and right_idx >= len_cookie:
                break
            if left == right :
                answer = max(answer, left)
                if right_idx < len_cookie - 1 :
                    right_idx += 1
                    right += cookie[right_idx]
                elif left_idx < -1 :
                    left_idx -= 1
                    left -= cookie[left_idx]
            if left > right:
                right_idx += 1
                if right_idx <= len_cookie:
                    continue
                right += cookie[right_idx]
            elif left < right :
                left_idx -= 1
                if left_idx < 0:
                    continue
                left += cookie[left_idx]

    return answer

무한 루프에 빠졌다. 🫥

기준을 0부터 쿠키 갯수 -1까지 하고 합이 더 작은 쪽에 쿠키를 더 주게 구현하려고 했다.

정리 안하고 막 구현하면 안 된다.🙄

 

🟨 다른 사람 풀이

# https://deok2kim.tistory.com/125
def solution(cookie):
    answer = 0
    n = len(cookie)
    
    for i in range(n - 1) :
        left_sum, left_idx = cookie[i], i
        right_sum, right_idx = cookie[i + 1], i + 1
        
        while True :
            if left_sum == right_sum :
                answer = max(answer, left_sum)
            
            if left_idx > 0 and left_sum <= right_sum :
                left_idx -= 1
                left_sum += cookie[left_idx]
            elif right_idx < n - 1 and right_sum <= left_sum :
                right_idx += 1
                right_sum += cookie[right_idx]
            else :
                break
        
    return answer

0부터 n-1까지 중심을 잡는다. ➡️ 두 형제가 쿠키 하나씩은 챙겨야 하니까~

왼쪽 쿠키 합과 오른쪽 쿠키 합이 같으면 answer을 갱신

쿠키 합이 더 작은 쪽에 다음 쿠키를 준다.

 

 

 

문제 출처 👇

https://school.programmers.co.kr/learn/courses/30/lessons/49995?language=python3 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

반응형

'coding test' 카테고리의 다른 글

[파이썬, Java] 인사고과  (0) 2023.04.12
[파이썬, Java] 호텔 방 배정  (0) 2023.04.11
[파이썬] 부대복귀  (0) 2023.04.11
[파이썬] 호텔 대실  (0) 2023.04.10
[파이썬] 과제 진행하기  (0) 2023.04.05