-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPourWater.java
More file actions
38 lines (31 loc) · 1.17 KB
/
PourWater.java
File metadata and controls
38 lines (31 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package array;
/**
* Description: https://leetcode.com/problems/pour-water
* Difficulty: Medium
* Time complexity: O(volume * n)
* Space complexity: O(1)
*/
public class PourWater {
public int[] pourWater(int[] heights, int volume, int k) {
int currentWaterPosition = k;
for (int drop = 0; drop < volume; drop++) {
// move droplet to the left
while (currentWaterPosition > 0
&& heights[currentWaterPosition] >= heights[currentWaterPosition - 1]) {
currentWaterPosition--;
}
// move droplet to the right
while (currentWaterPosition < heights.length - 1
&& heights[currentWaterPosition] >= heights[currentWaterPosition + 1]) {
currentWaterPosition++;
}
// move droplet back to the left if we have a plain terrain on the right
while (currentWaterPosition > k
&& heights[currentWaterPosition] == heights[currentWaterPosition - 1]) {
currentWaterPosition--;
}
heights[currentWaterPosition] += 1;
}
return heights;
}
}