forked from lemonbashar/java-algo-expert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaterArea.java
More file actions
66 lines (55 loc) · 1.78 KB
/
WaterArea.java
File metadata and controls
66 lines (55 loc) · 1.78 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package algoexpert.hard;
/*
PROBLEM:
Given an array of integers representing heights of pillars with constant width 1.
If the area is flooded, return the water area that the pillars will be able to hold.
EXAMPLE:
[0,8,0,0,5,0,0,10,0,0,1,1,0,3] -> 48
|
| |
| | | ,
_ | _ _ | _ _ | _ _ | | _ |
8 5 10 1 1 3
LOGIC:
Traverse Left to Right - find maxLeft
Traverse Right to Left - find maxRight
total capacity at each point = min(left, right) - height [given that min(left, right) > height]
SOLUTION:
1. L to R & vice versa traversal -> time : O(n) | space : O(n)
*/
public class WaterArea
{
public static void test()
{
int [] test = {0,8,0,0,5,0,0,10,0,0,1,1,0,3};
System.out.println(waterArea(test));
}
// time : O(n) | space : O(n)
// the function can be optimized to use just one array for storing min(left, right)
public static int waterArea(int[] heights)
{
if (heights.length == 0) return 0;
int [] maxLeft = new int[heights.length];
int [] maxRight = new int[heights.length];
maxLeft[0] = 0;
int currentMax = 0;
for (int i = 1; i < maxLeft.length; ++i)
{
maxLeft[i] = currentMax;
if (heights[i] > currentMax) { currentMax = heights[i]; }
}
currentMax = 0;
for (int i = maxRight.length - 1; i >= 0; --i)
{
maxRight[i] = currentMax;
if (heights[i] > currentMax) { currentMax = heights[i]; }
}
int waterArea = 0;
for (int i = 0; i < heights.length; ++i)
{
int min = Math.min(maxLeft[i], maxRight[i]);
if (min > heights[i]) waterArea = waterArea + min - heights[i];
}
return waterArea;
}
}