Skip to content

Commit 668dea7

Browse files
authored
Add files via upload
1 parent 1cfc699 commit 668dea7

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Arrays/Hourglass_Sum.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
'''
2+
Given a 6X6 2D Array, A:
3+
1 1 1 0 0 0
4+
0 1 0 0 0 0
5+
1 1 1 0 0 0
6+
0 0 0 0 0 0
7+
0 0 0 0 0 0
8+
0 0 0 0 0 0
9+
10+
An hourglass in A is a subset of values with indices falling in this pattern
11+
in A's graphical representation:
12+
a b c
13+
d
14+
e f g
15+
16+
There are 16 hourglasses in A, and an hourglass sum is the sum of an hourglass'
17+
values. Like here, the maximum hourglass sum is 7 for the hourglass in the top
18+
left corner.
19+
20+
Aim: Check all such hourglasses and print the maximum hourglass sum for the
21+
2D array entered by user.
22+
23+
'''
24+
25+
# getting the 2D array as input
26+
arr = []
27+
for _ in range(6):
28+
arr.append(list(map(int, input().rstrip().split())))
29+
30+
res = []
31+
# looping through the 2D array
32+
for x in range(0, 4):
33+
for y in range(0, 4):
34+
# selecting combinations that make an hourglass
35+
s = sum(arr[x][y:y+3]) + arr[x+1][y+1] + sum(arr[x+2][y:y+3])
36+
res.append(s)
37+
# printing out the maximum hourglass sum
38+
print(max(res))
39+
40+
'''
41+
42+
COMPLEXITY:
43+
44+
Time Complexity -> O(N^2)
45+
Space Complexity -> O(N)
46+
47+
Sample Input:
48+
0 0 1 2 3 0
49+
0 0 0 5 0 0
50+
1 0 0 7 1 0
51+
0 0 0 0 0 0
52+
0 1 1 1 0 1
53+
0 0 4 0 0 4
54+
55+
Sample Output:
56+
19
57+
58+
Explanation:
59+
The hourglass with the maximum sum is,
60+
1 2 3
61+
5
62+
0 7 1
63+
with the sum being 1 + 2 + 3 + 5 + 0 + 7 + 1 = 19
64+
65+
'''

0 commit comments

Comments
 (0)