BASHA TECH
[HackerRank][Python] 2D Arrays 본문
Task
Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.
Example
In the array shown above, the maximum hourglass sum is 7 for the hourglass in the top left corner.
Input Format
There are 6 lines of input, where each line contains 6 space-separated integers that describe the 2D Array A.
Constraints
- -9 <= A[i][j] <= 9
- 0 <= i, j <= 5
Output Format
Print the maximum hourglass sum in A.
if __name__ == '__main__':
# Create an empty list to store the input array
arr = []
# Take input of 6 lines, where each line contains 6 integers separated by spaces
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
# Initialize the maximum sum to None, indicating that we haven't found any valid hourglass sum yet
max_sum = None
# Loop through all valid sub-arrays (indices 0 to 3 for both rows and columns)
for i in range(4):
for j in range(4):
# Calculate hourglass sum using the formula: sum = top row + middle element + bottom row
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]
# Update maximum sum if the current sum is greater than the previous maximum sum
if max_sum is None or sum > max_sum:
max_sum = sum
# Print the maximum sum
print(max_sum)
In this code, we initialize max_sum to None to indicate that we haven't found any valid hourglass sum yet. We then loop through all valid sub-arrays and calculate the hourglass sum for each of them using the formula mentioned above. We then update the max_sum variable if the current sum is greater than the previous maximum sum. Finally, we print the max_sum variable.
'Activity > Coding Test' 카테고리의 다른 글
[HackerRank][Python] Inheritance (0) | 2023.04.24 |
---|---|
[HackerRank][Python] Binary Numbers (0) | 2023.04.17 |
[HackerRank][Python] Recursion 3 (0) | 2023.04.17 |
[HackerRank][Python] Dictionaries and Maps (0) | 2023.04.17 |
[HackerRank][Python] Arrays (0) | 2023.04.17 |