-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhour-glass-2D-array.py
executable file
·116 lines (85 loc) · 2.81 KB
/
hour-glass-2D-array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 27 22:09:02 2019
@author: USER
"""
# SOLVED!
"""
Problem Description:
Given a 6 X 6 2D Array, arr:
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 A to be a subset of values with indices falling
in this pattern in arr's graphical representation:
a b c
d
e f g
There are 16 hourglasses in A, and an hourglass sum is the sum of an
hourglass' values. Calculate the hourglass sum for every hourglass in arr,
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 16 hourglass values:
-63, -34, -9, 12,
-10, 0, 28, 23,
-27, -11, -2, 10,
9, 17, 25, 18
Our highest hourglass value is 28 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
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:
arr contains the following hourglasses:
1 1 1 1 1 0 .... 0 0 0
1 0 .... 0
1 1 1 1 1 0 .... 0 0 0
.
.
.
The hourglass with the maximum sum (19) is:
2 4 4
2
1 2 4
"""
import sys
def hourglassSum(arr):
max_sum = -sys.maxsize - 1
for i in range(len(arr)-2):
rui = i # index for upper row
rmi = i + 1 # index for middle row
rli = i + 2 # index for lower row
for j in range(len(arr[0])-2):
cui = j # index for upper column
cmi = j + 1 # index for middle column
cli = j + 2 # index for lower column
total_for_upper = arr[rui][cui] + arr[rui][cmi] + arr[rui][cli]
total_for_mid = arr[rmi][cmi]
total_for_lower = arr[rli][cui] + arr[rli][cmi] + arr[rli][cli]
total = total_for_upper + total_for_mid + total_for_lower
max_sum = max(max_sum, total)
return max_sum