We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I’m new to Python and couldn’t find a more intuitive solution for this problem, so I thought I’d share mine. Feedback or improvements are very welcome!
My Pyhton solution:
def hourglassSum(arr):
# Write your code here
evey_sum_hourglass_1 = []
evey_sum_hourglass_2 = []
evey_sum_hourglass_3 = []
evey_sum_hourglass_4 = []
for i in range(0,4, +1):
line_sum_1 = arr[i +1][1]
for j in range(0, 3, +1):
line_sum_1 += arr[i][j] + arr[i+2][j]
evey_sum_hourglass_1.append(line_sum_1)
for i in range(0,4, +1):
line_sum_2 = arr[i +1][2]
for j in range(1, 4, +1):
line_sum_2 += arr[i][j] + arr[i+2][j]
evey_sum_hourglass_2.append(line_sum_2)
for i in range(0,4, +1):
line_sum_3 = arr[i +1][3]
for j in range(2, 5, +1):
line_sum_3 += arr[i][j] + arr[i+2][j]
evey_sum_hourglass_3.append(line_sum_3)
for i in range(0,4, +1):
line_sum_4 = arr[i +1][4]
for j in range(3, 6, +1):
line_sum_4 += arr[i][j] + arr[i+2][j]
evey_sum_hourglass_4.append(line_sum_4)
all_sum = evey_sum_hourglass_1 + evey_sum_hourglass_2 + evey_sum_hourglass_3 + evey_sum_hourglass_4
max_sum = max(all_sum)
return max_sum
My idea was to divide the original 6x6 matrix into 6x3 matrices. Each for loop adds all the hourglasses in each 6x3 matrix, so 4 loops were needed to cover the 6x6 matrix.
For larger/smaller matrices, it would be necessary to adjust the loop parameters and add/remove loops, but it worked. However, I don't think it would be good for NxM matrices.
2D Array - DS
You are viewing a single comment's thread. Return to all comments →
I’m new to Python and couldn’t find a more intuitive solution for this problem, so I thought I’d share mine. Feedback or improvements are very welcome!
My Pyhton solution:
def hourglassSum(arr): # Write your code here
Does it work? what if you have more than 4 row
Yes, it works
My idea was to divide the original 6x6 matrix into 6x3 matrices. Each for loop adds all the hourglasses in each 6x3 matrix, so 4 loops were needed to cover the 6x6 matrix.
For larger/smaller matrices, it would be necessary to adjust the loop parameters and add/remove loops, but it worked. However, I don't think it would be good for NxM matrices.
hi nizmu, all what u need is one variable to store the sum and one for max_sum
How much data does Streaming use - explanation