File tree 1 file changed +63
-0
lines changed
1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ //Here is the two pointer approach
2
+ //by taking auxaliary space of O(n)
3
+
4
+ //Here I'm giving Both C++ & java Solution
5
+
6
+ // C++ Solution //and for java solution scroll down
7
+
8
+ class Solution {
9
+ public:
10
+ int trap(vector<int>&height) {
11
+ //Space COmplexity O(n)
12
+ //Time Complexity O(n)
13
+ int n = height.size();
14
+
15
+ vector<int>left(n);
16
+ left[0] = height[0];
17
+
18
+ for(int i=1;i<n;i++){
19
+ left[i] = max(left[i-1],height[i]);
20
+ }
21
+
22
+ vector<int>right(n);
23
+ right[n-1] = height[n-1];
24
+
25
+ for(int i=n-2;i>=0;i--){
26
+ right[i] = max(right[i+1],height[i]);
27
+ }
28
+
29
+ int ans =0;
30
+ for(int i=0;i<n;i++){
31
+ ans += (min(right[i],left[i])-height[i]);
32
+ }
33
+ return ans;
34
+
35
+ }
36
+ };
37
+
38
+ // Java Solution
39
+
40
+ class Solution {
41
+ public int trap(int[] height) {
42
+ //SPace Complexitiy O(n)
43
+ int n = height.length;
44
+ int left[] = new int[n];
45
+ int right[] = new int[n];
46
+ left[0] = height[0];
47
+ for(int i=1;i<n;i++){
48
+ left[i] = Math.max(left[i-1],height[i]);
49
+ }
50
+ right[n-1] = height[n-1];
51
+ for(int i=n-2;i>=0;i--){
52
+ right[i] = Math.max(right[i+1],height[i]);
53
+ }
54
+ int ans=0;
55
+ for(int i=0;i<n;i++){
56
+ //formula
57
+ ans += (Math.min(left[i],right[i])-height[i]);
58
+ }
59
+ return ans;
60
+ }
61
+ };
62
+
63
+
You can’t perform that action at this time.
0 commit comments