Pour Water

medium simulation arrays greedy

Problem

Given heights of terrain and an index k where water drops fall, simulate V drops. Each drop tries to flow left to the lowest position, otherwise right to the lowest position, otherwise rests at k. Return the resulting heights.

Inputheights=[2,1,1,2,1,2,2], V=4, K=3
Output[2,2,2,3,2,2,2]
Four units of water poured at index 3 settle as shown.

def pourWater(heights, V, K):
    for _ in range(V):
        placed = False
        for d in (-1, 1):
            i, j = K, K
            while 0 <= i+d < len(heights) and heights[i+d] <= heights[i]:
                if heights[i+d] < heights[i]:
                    j = i+d
                i += d
            if j != K:
                heights[j] += 1
                placed = True
                break
        if not placed:
            heights[K] += 1
    return heights
function pourWater(heights, V, K) {
  for (let v = 0; v < V; v++) {
    let placed = false;
    for (const d of [-1, 1]) {
      let i = K, j = K;
      while (i+d >= 0 && i+d < heights.length && heights[i+d] <= heights[i]) {
        if (heights[i+d] < heights[i]) j = i+d;
        i += d;
      }
      if (j !== K) { heights[j]++; placed = true; break; }
    }
    if (!placed) heights[K]++;
  }
  return heights;
}
int[] pourWater(int[] heights, int V, int K) {
    for (int v = 0; v < V; v++) {
        boolean placed = false;
        for (int d : new int[]{-1, 1}) {
            int i = K, j = K;
            while (i+d >= 0 && i+d < heights.length && heights[i+d] <= heights[i]) {
                if (heights[i+d] < heights[i]) j = i+d;
                i += d;
            }
            if (j != K) { heights[j]++; placed = true; break; }
        }
        if (!placed) heights[K]++;
    }
    return heights;
}
vector<int> pourWater(vector<int>& heights, int V, int K) {
    for (int v = 0; v < V; v++) {
        bool placed = false;
        for (int d : {-1, 1}) {
            int i = K, j = K;
            while (i+d >= 0 && i+d < (int)heights.size() && heights[i+d] <= heights[i]) {
                if (heights[i+d] < heights[i]) j = i+d;
                i += d;
            }
            if (j != K) { heights[j]++; placed = true; break; }
        }
        if (!placed) heights[K]++;
    }
    return heights;
}
Time: O(V*n) Space: O(1)