def balancedSums(arr): n = len(arr) for i in range(0, n): lsum = sum(arr[0 : i]) rsum = sum(arr[i + 1 : n]) if lsum == rsum: return "YES" return "NO"
I am getting all test cases but two, failing due to timeout. What are my options?
Advertisement
Answer
You can do something like that:
def balancedSums(arr): lsum = 0 rsum = sum(arr) n = len(arr) for i in range(0, n): rsum -= arr[i] if lsum == rsum: return "YES" lsum += arr[i] return "NO"
The time-complexity of this is O(n)