Problem statement

https://leetcode.com/problems/pour-water/

Solution

Here we just need to do simulation of process: first try left direction and move i while it is not increasing. Also keep best position we will move only if our level decreased. Then do the same steps in right direction.

Complexity

Time complexity is O(Vn), space is O(n) to return answer. Good question, if we can do better.

Code

class Solution:
    def pourWater(self, heights, V, K):
        for _ in range(V):
            i, best, n = K, K, len(heights)
            for d in [-1,1]:
                while n > i+d >= 0 and heights[i+d] <= heights[i]:
                    if heights[i+d] < heights[i]: best = i +d
                    i += d
            heights[best] += 1
        
        return heights