-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiagonal_difference.py
More file actions
70 lines (51 loc) · 1.7 KB
/
Copy pathdiagonal_difference.py
File metadata and controls
70 lines (51 loc) · 1.7 KB
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
# 17 03 2022
# Link: https://www.hackerrank.com/challenges/three-month-preparation-kit-diagonal-difference/problem
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
# Write your code here
length_of_column = len(arr)
diag_1_sum, diag_2_sum = 0, 0
"""
for i, row in enumerate(arr):
for j, value in enumerate(row):
if i == j and i + j == length_of_column - 1:
diag_1_sum += arr[i][j]
diag_2_sum += arr[i][j]
elif i == j:
diag_1_sum += arr[i][j]
elif i + j == length_of_column - 1:
diag_2_sum += arr[i][j]
"""
for i in range(length_of_column):
for j in range(length_of_column):
if i == j and i + j == length_of_column - 1:
diag_1_sum += arr[i][j]
diag_2_sum += arr[i][j]
elif i == j:
diag_1_sum += arr[i][j]
elif i + j == length_of_column - 1:
diag_2_sum += arr[i][j]
return abs(diag_1_sum-diag_2_sum)
# Not a great solution as it is O(n^2)
# O(n^2) Time Complexity
# O(1) Space Complexity
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
fptr.write(str(result) + '\n')
fptr.close()