[프로그래머스] 코딩테스트 연습 - 연습문제 Level 2 땅따먹기

uoahy·2021년 9월 28일
0

Solution.java

class Solution {
    int solution(int[][] land) {
        int answer = 0;

        for (int i = 1; i < land.length; i++) {
            int max1 = 0, max2 = 0;
            for (int j = 0; j < 4; j++) {
                if (land[i - 1][j] > max2) {
                    if (land[i - 1][j] > max1) {
                        max2 = max1;
                        max1 = land[i - 1][j];
                    }
                    else {
                        max2 = land[i - 1][j];
                    }
                }
            }
            
            for (int j = 0; j < 4; j++) {
                land[i][j] += (land[i - 1][j] != max1) ? max1 : max2;
            }
        }
        
        for (int i = 0; i < 4; i++) {
            answer = Math.max(answer, land[land.length - 1][i]);
        }

        return answer;
    }
}

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

0개의 댓글