ans = 0 for i in range(n): x2, x5 = 0, 0 for j in range(i, n): x2 += factor_2_nums[j] x5 += factor_5_nums[j] if x2 <= total2 - k and x5 <= total5 - k: print(i, j, nums[i: j+1]) ans += 1 else: break
print(ans)
这样时间复杂度为 O(n2)
改进:使用前缀和+二分查找
1 2 3 4 5 6 7 8 9 10 11
prefix2 = list(accumulate(factor_2_nums, initial=0)) prefix5 = list(accumulate(factor_5_nums, initial=0)) ans = 0 for i in range(n+1): # 固定左端点,二分查找右端点 # bisect_right找到的是满足大于条件的第一个下标.第二个参数可以理解为寻找从prefix2[i]开始,与其相差total2-k的元素 j2 = bisect_right(prefix2, total2 - k + prefix2[i]) j5 = bisect_right(prefix5, total5 - k + prefix5[i]) ans += min(j2, j5) - i - 1 print(nums[i: min(j2, j5) - 1]) print(ans)