Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 25 additions & 52 deletions TrappingRainWater/TrappingRainWater.cpp
Original file line number Diff line number Diff line change
@@ -1,58 +1,31 @@
// O(n) time, O(n) space
class Solution {
public:
int trap(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

int max_from_left[n];
int max_from_right[n];

max_from_left[0] = A[0];
for (int i = 1; i < n; i++)
max_from_left[i] = max(max_from_left[i-1], A[i]);

max_from_right[n-1] = A[n-1];
for (int i = n - 2; i >= 0; i--)
max_from_right[i] = max(max_from_right[i+1], A[i]);

int water = 0;
for (int i = 1; i < n - 1; i++) {
int min_height = min(max_from_left[i-1], max_from_right[i+1]);
if (min_height > A[i])
water += min_height - A[i];
}
return water;
}
};
if(n<=1)
return 0;
int start = 0;
int end = n-1;

// O(n) time, O(1) space
class Solution {
public:
int trap(int A[], int n) {
int maxh = 0;
int water = 0;
int temp = 0;
for (int i = 0; i < n; i++) {
if (A[i] <= maxh) {
temp += maxh - A[i];
} else {
maxh = A[i];
water += temp;
temp = 0;
}
}
maxh = 0;
temp = 0;
for (int i = n - 1; i >= 0; i--) {
if (A[i] < maxh) {
temp += maxh - A[i];
} else {
maxh = A[i];
water += temp;
temp = 0;
}
}
return water;
int leftMax = A[start];
int rightMax = A[end];

int capacity;
while(start < end){
if(leftMax <= rightMax){
if(A[start+1] < leftMax){
capacity += (leftMax - A[start+1]);
}else{
leftMax = A[start+1];
}
start++;
}else{
if(A[end-1] < rightMax){
capacity += (rightMax - A[end-1]);
}else
rightMax = A[end-1];
end--;
}
}
return capacity;
}
};