I am trying to solve this problem statement on codechef. The problem statement in a nutshell is: Find out the value(explanation coming up) of array with 'n' elements after updating the array each time, 'q' times.
value of the array means, sum of the absolute differences of consecutive elements of the array. e.g.
array = [1,2,3,4,5]
value(array) = abs(1-2) + abs(2-3) + ... + abs(4-5)
I am learning python (3rd day into it) and am trying to solve the problem using the following python code.
def update(arr,find,replace):
for i in range(len(arr)):
if arr[i]==find:
arr[i]=replace
def value(arr):
sum = 0
for i in range(len(arr)-1):
sum = sum + abs(arr[i]-arr[i+1])
return sum
test_case = int(input())
while test_case > 0 :
n,q = map(int,input().split(" "))
array = list(map(int,input().split()))
for i in range(q):
x,y = map(int,input().split(" "))
update(array,x,y)
print(value(array))
test_case -= 1
This code, when I run on my machine is yielding correct results for custom test cases (even with large input) but on the site exceeds the time limit. Is there any way we can optimise the code to fit it into the given constraints...... time complexity : < 2secs and size : 50000bytes?