Let’s also start by identifying how we’ll move on this grid to find the maximum product.
Let’s notice that if we move along every position on the grid we can cover each possibility with four directions: up, diagonally up from left to right, right, and diagonally down from left to right.
There’s no need to have a left direction, a down direction, or the diagonal directions from right to left because the above directions cover all scenarios. Let’s demonstrate this with an example. At position Grid[7,9] = 26 (row 7, column 9) the product in the diagonally down from the left to right direction the product is \(26 \times 63 \times 78 \times 14\). This is the same product when we’re at position Grid[10,12] = 14 in the diagonally up from the right to left direction which is \(14 \times 78 \times 63 \times 28\).
The same will be true with the other directions. Therefore we can just consider the previous four directions because we can elimintate any unnecessary compututions for efficiency purposes.
In our code we can define the following - product1 refers to the product in the up direction - product2 refers to the product in the diagonally up direction - product3 refers to the product in the right direction - product4 refers to the product in the diagonally down direction
Therefore we have the following code
Code
# Initialize productsmax_product =1product1 =1product2 =1product3 =1product4 =1prod_vector = []# Used to determine position and direction of productpos_m =0pos_n =0direction =0for rows =1:20for cols =1:20# Reset products and prod_vector when starting new position on grid product1 =1 product2 =1 product3 =1 product4 =1 prod_vector = []for up =1:4# Boundary caseif (rows - up +1) ==0breakend product1 = product1*Grid[rows - up +1, cols] endfor diagonal_up =1:4# Boundary caseif ((rows - diagonal_up +1) ==0) | ((cols + diagonal_up -1) ==21)breakend product2 = product2*Grid[rows - diagonal_up +1, cols + diagonal_up -1]endfor right =1:4# Boundary caseif (cols + right -1) ==21breakend product3 = product3*Grid[rows, cols + right -1]endfor diagonal_down =1:4# Boundary caseif ((rows + diagonal_down -1) ==21) | ((cols + diagonal_down -1) ==21)breakend product4 = product4*Grid[rows + diagonal_down -1, cols + diagonal_down -1]end# Add all products to prod_vector prod_vector =push!(prod_vector, product1, product2, product3, product4)# Update max product at every postion if condition is true, find max productif max_product <maximum(prod_vector) direction =argmax(prod_vector) max_product =maximum(prod_vector) pos_m = rows pos_n = colsendendendprintln("max_product = ", max_product)println("row = ", pos_m)println("col = ", pos_n)println("direction = ", direction)
max_product = 70600674
row = 16
col = 4
direction = 2
Therefore we have that the greatest product is \(70,600,674 = 87 \times 97 \times 94 \times 89\) which is at position Grid[16,4] (row 16, column 4)in the diagonally up direction.