class Solution:
def wateringPlants(self, plants: List[int], capacity: int) -> int:
n = len(plants)
back = []
i = 0
cnt = 0 #每趟需要的水量
# 每到一个位置,检查水量是否用完
while i < n and cnt <= capacity:
# 尝试给i植物浇水
cnt += plants[i]
# 超过,说明到i处水量不够用,在前一位i-1就要返回
if cnt > capacity:
cnt = plants[i]
back.append(i-1+1) # +1是到取水处的总路程
# 没超过,但是到最后一株植物也要统计单程
if i == n-1:
back.append(i+1)
i+= 1
res = 0
for b in back: # 累加所有来回距离
res += (b) * 2
res -= back[-1] #最后一株算了两次
return res