原题链接:PTA | 程序设计类实验辅助教学平台
Tips:以下Python代码仅个人理解,非最优算法,仅供参考!多学习其他大佬的AC代码!
def count_purchase_options(N, M, prices):
start = 0
current_sum = 0
total_count = 0
for end in range(N):
current_sum += prices[end]
# 移动 start 指针,直到 current_sum <= M
while current_sum > M and start <= end:
current_sum -= prices[start]
start += 1
# 记录可购买方案数
total_count += (end - start + 1) # 当前end可以形成的所有子数组的数量
# print(start,end,total_count)
return total_count
# 主程序
N, M = map(int, input().strip().split()) # 读取土地块数和现金量
prices = list(map(int, input().strip().split())) # 读取每块土地的价格
result = count_purchase_options(N, M, prices) # 计算可购买方案数
print(result) # 输出结果
标签:买地,end,start,Python,sum,current,1120,prices
From: https://blog.csdn.net/m0_56677113/article/details/143021472