티끌모아 연산

모래시계 - 알고리즘

Dev.Kyu 2019. 4. 18. 11:17

https://www.hackerrank.com/challenges/2d-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays

 

2D Array - DS | HackerRank

How to access and use 2d-arrays.

www.hackerrank.com

 

Problem

Given a  2D Array, :

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

We define an hourglass in  to be a subset of values with indices falling in this pattern in 's graphical representation:

a b c
   d
e f g

There are  hourglasses in , and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum.

For example, given the 2D array:

-9 -9 -9 1 1 1
0 -9 0 4 3 2
-9 -9 -9 1 2 3

0 0 8 6 6 0
0 0 0 -2 0 0
0 0 1 2 4 0

We calculate the following  hourglass values:

-63, -34, -9, 12
-10, 0, 28, 23
-27, -11, -2, 10
9, 17, 25, 18

Our highest hourglass value is  from the hourglass:

0 4 3
   1
8 6 6

Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge.

Function Description

Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array.

hourglassSum has the following parameter(s):

  • arr: an array of integers

Input Format

Each of the  lines of inputs  contains  space-separated integers .

Constraints

  • -9 <= arr[i][j] <= 9
  • 0 <= i,j <= 9

Output Format

Print the largest (maximum) hourglass sum found in .

Sample Input

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

Sample Output

19

Explanation

 contains the following hourglasses:

The hourglass with the maximum sum (19) is:

2 4 4
   2
1 2 4

 

Result

fun hourglassSum(arr: Array<Array<Int>>): Int {

        var maxNum = -55

        for (i in 0..arr.size - 3) {
            for (j in 0..arr[i].size - 3) {
                val sum = arr[i][j] + arr[i][j+1] + arr[i][j + 2] + arr[i+1][j+1] + arr[i + 2][j] + arr[i + 2][j+1] + arr[i + 2][j + 2]
                if(sum > maxNum) maxNum = sum
            }
        }

        return maxNum

    }

 


세계 최강을 꿈꾸는 안드로이드 Front-End 개발자입니다.

 

Github 주소: github.com/rkswlrbduf

이전 블로그 주소: blog.naver.com/rkswlrbduf => 블로그 이전중...