HackerRank Java 2D Array

문제 링크 : https://www.hackerrank.com/challenges/java-2d-array/problem

간략한 설명 => 6 * 6 이차원 배열에서 HourGlass 모양의 합 중 가장 큰 합을 출력해내면 된다.

ex) 1 1 1 0 0 0
      0 1 0 0 0 0
      1 1 1 0 0 0
      0 0 0 1 2 3
      0 0 0 1 3 1
      0 0 0 2 2 2

1 + 2 + 3 + 3 + 2 + 2 + 2 = 15

출력 15


가장 큰 HourGlass 는 1 2 3
                                        3
                                     2 2 2


접근 방법 : 모래시계는 무조건 3 * 3 이차원 배열속에 있다.
                    따라서 모든 3*3 이차원 배열의 부분을 뽑아내서 합을 구한 후
                   최대값을 출력 해준다.



import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
int[][] arr = new int[6][6];

for (int i = 0; i < 6; i++) {
String[] arrRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

for (int j = 0; j < 6; j++) {
int arrItem = Integer.parseInt(arrRowItems[j]);
arr[i][j] = arrItem;
}
}
int maxValue = Integer.MIN_VALUE;
for (int a = 0; a < 4; a++) {
for (int i = 0; i < 4; i++) {
int tempValue = 0;
int rowFlag = -1;
for (int j = i; j < i+3; j++) {
rowFlag++;
int colFlag = -1;
for (int k = a; k < a+3; k++) {
colFlag++;
if(rowFlag == 1) {
if (colFlag == 1){
tempValue += arr[j][k];
}
} else {
tempValue += arr[j][k];
}
}
}
maxValue = Math.max(maxValue, tempValue);
}
}
System.out.println(maxValue);
scanner.close();
}
}

댓글

이 블로그의 인기 게시물

Spring Boot Actuator readiness, liveness probes on k8s

About idempotent

About JVM Warm up

About G1 GC

About Kafka Basic

sneak peek jitpack

About ZGC

HackerRank Java Between Two Sets

Optimistic Concurrency Control VS Pessimistic Concurrency Control - What should i choose?

I need to know a little JVM