Skip to main content
 首页 » 编程设计

python之Codility之使用 Python 进行磁带平衡训练

2025年05月04日16zhengyun_ustc

A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape. Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1]. The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])| In other words, it is the absolute difference between the sum of the first part and the sum of the second part.

def solution(A): 
N = len(A) 
my_list = [] 
for i in range(1, N): 
    first_tape = sum(A[:i - 1]) + A[i] 
    second_tape = sum(A[i - 1:]) + A[i] 
    difference = abs(first_tape - second_tape) 
    my_list.append(difference) 
print(min(my_list)) 
return min(my_list) 

我的解决方案的正确性为 100%,但性能为 0%。 我认为它应该是 O(N) 但我的时间复杂度是 O(N*N)。 任何人都可以给我建议吗?

请您参考如下方法:

您可以将您的代码更改为类似下面的代码以具有复杂性ON)。

def solution(A):           
    s = sum(A) 
    m = float('inf') 
    left_sum = 0 
    for i in A[:-1]: 
        left_sum += i 
        m = min(abs(s - 2*left_sum), m) 
    return m