알고리즘/문자열, 정렬

[알고리즘] 격자판 최대합 with Java, 이중 for문

VIPeveloper 2022. 3. 5. 15:09
728x90
반응형

오늘 배운 것

1. 문제 풀이

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        int i = kb.nextInt();
        int[][] arr = new int[i][i];
        for (int j = 0; j < arr.length; j++) {
            for (int k = 0; k < arr.length; k++) {
                arr[j][k] = kb.nextInt();
            }
        }
        solution(i,arr);
    }

    private static void solution(int i, int[][] arr) {
        ArrayList<Integer> answer = new ArrayList<>();

        for (int j = 0; j < arr.length; j++) {
            int tmp = 0;
            for (int k = 0; k < arr.length; k++) {
                tmp += arr[j][k];
            }
            answer.add(tmp);
        }

        for (int j = 0; j < arr.length; j++) {
            int tmp = 0;
            for (int k = 0; k < arr.length; k++) {
                tmp += arr[k][j];
            }
            answer.add(tmp);
        }

        int tmp = 0;
        for (int j = 0; j < arr.length; j++) {
            tmp += arr[j][j];
        }
        answer.add(tmp);

        tmp = 0;
        for (int j = 0; j < arr.length; j++) {
            tmp += arr[j][arr.length-1-j];
        }
        answer.add(tmp);

        int max_num = -1;
        for (int j = 0; j < answer.size(); j++) {
            if(max_num < answer.get(j)){
                max_num = answer.get(j);
            }
        }

        System.out.println(max_num);
    }
}

. 강의에서는 더 깔끔하게 풀었다. 4단계 -> 2단계로 줄이셨음.

private static void solution2(int i, int[][] arr) {
    int sum1,sum2;
    int answer = -1;
    for (int j = 0; j < arr.length; j++) {
        sum1=sum2=0;
        for (int k = 0; k < arr.length; k++) {
            sum1+=arr[j][k];
            sum2+=arr[k][j];
        }
        answer = Math.max(answer,sum1);
        answer = Math.max(answer,sum2);
    }
    sum1=sum2=0;
    for (int j = 0; j < arr.length; j++) {
        sum1+=arr[j][j];
        sum2+=arr[j][arr.length-1-j];
    }
    answer = Math.max(answer,sum1);
    answer = Math.max(answer,sum2);

    System.out.println(answer);
}
728x90
반응형