I'm completely new to time complexity problems. I'm writing Python code for a Codility exercise and the code I've written returns time out error with a time complexity of O(N*N). The expected time complexity is O(N).
Given a list of integers A,
I'm trying to compute the minimum difference between the sum of A[0:i] and the sum of A[i:], for all index i in A.
Here's my solution:
def solution(A):
# write your code in Python 2.7
a=[]
for i in range(1,len(A)):
a.append(abs(sum(A[0:i])-sum(A[i:len(A)+1])))
return min(a)
I tried to improve the code by implementing the following
import sys
def solution(A):
# write your code in Python 2.7
a=sys.maxint
for i in range(1,len(A)):
temp=abs(sum(A[0:i])-sum(A[i:len(A)+1]))
if temp<a:
a=temp
return a
I still get the same complexity. I understand the abs step is taking a lot of time to compute. How do I reduce time complexity for this code? Is there an intuitive way of looking at time complexity problems?