Skip to content

2105. Watering Plants II

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {
    int ans = 0;
    int i = 0;
    int j = plants.size() - 1;
    int canA = capacityA;
    int canB = capacityB;

    while (i < j) {
      ans += (canA < plants[i]) + (canB < plants[j]);
      if (canA < plants[i])
        canA = capacityA;
      if (canB < plants[j])
        canB = capacityB;
      canA -= plants[i++];
      canB -= plants[j--];
    }

    return ans + (i == j && max(canA, canB) < plants[i]);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int minimumRefill(int[] plants, int capacityA, int capacityB) {
    int ans = 0;
    int i = 0;
    int j = plants.length - 1;
    int canA = capacityA;
    int canB = capacityB;

    while (i < j) {
      ans += (canA < plants[i] ? 1 : 0) + (canB < plants[j] ? 1 : 0);
      if (canA < plants[i])
        canA = capacityA;
      if (canB < plants[j])
        canB = capacityB;
      canA -= plants[i++];
      canB -= plants[j--];
    }

    return ans + (i == j && Math.max(canA, canB) < plants[i] ? 1 : 0);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
    ans = 0
    i = 0
    j = len(plants) - 1
    canA = capacityA
    canB = capacityB

    while i < j:
      ans += (canA < plants[i]) + (canB < plants[j])
      if canA < plants[i]:
        canA = capacityA
      if canB < plants[j]:
        canB = capacityB
      canA -= plants[i]
      canB -= plants[j]
      i += 1
      j -= 1

    return ans + (i == j and max(canA, canB) < plants[i])