-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargestProductInGrid.py
96 lines (83 loc) · 2.59 KB
/
LargestProductInGrid.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
grid = []
with open("grid.txt") as f:
for line in f:
grid.append(line.rstrip("\n").split())
largest = 0
for x in range(len(grid)):
for y in range(len(grid[x])):
product = 0
# Up
if x > 2:
prod = (
int(grid[x][y])
* int(grid[x - 1][y])
* int(grid[x - 2][y])
* int(grid[x - 3][y])
)
product = prod if prod > product else product
# Down
if x < len(grid) - 3:
prod = (
int(grid[x][y])
* int(grid[x + 1][y])
* int(grid[x + 2][y])
* int(grid[x + 3][y])
)
product = prod if prod > product else product
# Left
if y > 2:
prod = (
int(grid[x][y])
* int(grid[x][y - 1])
* int(grid[x][y - 2])
* int(grid[x][y - 3])
)
product = prod if prod > product else product
# Right
if y < len(grid[x]) - 3:
prod = (
int(grid[x][y])
* int(grid[x][y + 1])
* int(grid[x][y + 2])
* int(grid[x][y + 3])
)
product = prod if prod > product else product
# Top-Left
if x > 2 and y > 2:
prod = (
int(grid[x][y])
* int(grid[x - 1][y - 1])
* int(grid[x - 2][y - 2])
* int(grid[x - 3][y - 3])
)
product = prod if prod > product else product
# Top-Right
if x > 2 and y < len(grid[x]) - 3:
prod = (
int(grid[x][y])
* int(grid[x - 1][y + 1])
* int(grid[x - 2][y + 2])
* int(grid[x - 3][y + 3])
)
product = prod if prod > product else product
# Bottom-Left
if x < len(grid) - 3 and y > 2:
prod = (
int(grid[x][y])
* int(grid[x + 1][y - 1])
* int(grid[x + 2][y - 2])
* int(grid[x + 3][y - 3])
)
product = prod if prod > product else product
# Bottom-Right
if x < len(grid) - 3 and y < len(grid[x]) - 3:
prod = (
int(grid[x][y])
* int(grid[x + 1][y + 1])
* int(grid[x + 2][y + 2])
* int(grid[x + 3][y + 3])
)
product = prod if prod > product else product
if product > largest:
largest = product
print(largest)