给植物浇水
思路
使用双指针法遍历 plant
数组:
- 对于 Alice,如果当前水量不足以浇灌植物,则需要将水桶加满,重灌溉次数加 1;如果水量足够,则水桶减少对应的浇水量,左指针向右移动。
- 对于 Bob,处理方式类似:如果水量不足,则重灌溉次数加 1;如果水量足够,则水桶减少对应的浇水量,右指针向左移动。
此外,还需要考虑两人指针相遇时的情况:如果 Alice 的水量大于 Bob,但仍不足以浇灌当前植物,则重灌溉次数需加 1;同理,如果 Bob 的水量不足,也需加 1。
class Solution:def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:if not plants:return 0n=len(plants)left=0right=n-1watera=capacityAwaterb=capacityBcount=0while left<right:if watera<plants[left]:watera=capacityAcount+=1#够水的情况watera-=plants[left]left+=1if waterb<plants[right]:waterb=capacityBcount+=1waterb-=plants[right]right-=1#还要考虑相等的情况,中间还有植物if left==right:if watera>=waterb:#Alice浇水if watera<plants[left]:count+=1else:if waterb<plants[left]:count+=1return count