Fork me on GitHub

Pour Water

Description

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

Solution

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
class Solution {
public:
vector<int> pourWater(vector<int>& heights, int V, int K) {
vector<int> ret = heights;
if (K < 0 || K >= heights.size() ) return heights;
for (int i = 0; i < V; ++i) {
//Check left
int index = K - 1;
int minIndex = -1;
while(index >= 0 && ret[index] <= ret[index + 1]) {
if (ret[index] < ret[index + 1]) minIndex = index;
--index;
}
if (minIndex != - 1) {
++ret[minIndex];
continue;
}

//Check right
index = K + 1;
minIndex = -1;
while(index < ret.size() && ret[index] <= ret[index - 1]) {
if (ret[index] < ret[index - 1]) minIndex = index;
++index;
}
if (minIndex != -1) {
++ret[minIndex];
continue;
}
//Stay here
++ret[K];
}

return ret;
}
};