2079.给植物浇水

https://leetcode-cn.com/problems/watering-plants/

一、模拟

用一个back数组记录每次水不够需要回去打水的位置,总路程就累加每次来回距离,注意最后一次不需要回去只算单程

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

最后更新于