Skip to content

755. Pour Water 👎

  • Time: $O(\texttt{volume} + k)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  vector<int> pourWater(vector<int>& heights, int volume, int k) {
    int i = k;

    while (volume-- > 0) {
      while (i > 0 && heights[i] >= heights[i - 1])
        --i;
      while (i + 1 < heights.size() && heights[i] >= heights[i + 1])
        ++i;
      while (i > k && heights[i] == heights[i - 1])
        --i;
      ++heights[i];
    }

    return heights;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int[] pourWater(int[] heights, int volume, int k) {
    int i = k;

    while (volume-- > 0) {
      while (i > 0 && heights[i] >= heights[i - 1])
        --i;
      while (i + 1 < heights.length && heights[i] >= heights[i + 1])
        ++i;
      while (i > k && heights[i] == heights[i - 1])
        --i;
      ++heights[i];
    }

    return heights;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def pourWater(self, heights: list[int], volume: int, k: int) -> list[int]:
    i = k

    while volume > 0:
      volume -= 1
      while i > 0 and heights[i] >= heights[i - 1]:
        i -= 1
      while i + 1 < len(heights) and heights[i] >= heights[i + 1]:
        i += 1
      while i > k and heights[i] == heights[i - 1]:
        i -= 1
      heights[i] += 1

    return heights