File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ //LeetCode 11. Container with most water
2
+ //Question - https://leetcode.com/problems/container-with-most-water/
3
+
4
+ class Solution {
5
+ public int maxArea (int [] height ) {
6
+ int start = 0 ;
7
+ int end = height .length - 1 ;
8
+ int maxWater = 0 ;
9
+
10
+ /*
11
+ Brute force solution would be to evaluate all containers. This will take
12
+ O(n^2) time. This can be avoided by considering the fact that the
13
+ maximum water a container can hold is restricted by the minimum of the
14
+ two sides. The minimum value acts as a limiting factor.
15
+
16
+ There is no point in pairing-up this minimum value with other greater values
17
+ as the height is limited by this value.
18
+
19
+ To gain maximum profit from this value, we need to pair it with the
20
+ farthest value which is equal to or greater than this value. This is
21
+ the maximum water we can retain with this value and so it is safe to
22
+ move the pointer pointing at this minimum value.
23
+ */
24
+
25
+ while (start < end ){
26
+ int water = Math .min (height [start ], height [end ]) * (end - start );
27
+ maxWater = Math .max (maxWater , water );
28
+
29
+ if (height [start ] < height [end ]) start ++;
30
+ else end --;
31
+ }
32
+
33
+ return maxWater ;
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments