I was solving this problem in Python3 on the Codechef website. Here I've to split an array such that the absolute difference between the maximum of both the arrays is maximum.
For example, if the input array is [1, 3, -3] then it can be split in two ways:
Way-1:
[1] and [3,-3] --> Absolute difference between max of arrays is 3-1 = 2
Way-2:
[1,3] and [-3] --> Absolute difference between max of arrays is 3 - (-3) = 6
So the max difference is 6, which is the answer.
Below is my code:
def max_difference(a):
max_diff = 0
for i in range(len(a) -1):
local_diff = abs(max(a[:i+1]) - max(a[i+1:]))
if max_diff < local_diff:
max_diff = local_diff
return max_diff
if __name__ == '__main__':
arr_count = int(input())
arr = list(map(int, input().rstrip().split()))
res = max_difference(arr)
print(res)
Can you please tell me if this code fine? What improvements can be done?