-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathContainerWithMostWater.java
More file actions
111 lines (63 loc) · 1.97 KB
/
ContainerWithMostWater.java
File metadata and controls
111 lines (63 loc) · 1.97 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
Container With Most Water
Problem Description
Given n non-negative integers A[0], A[1], ..., A[n-1] , where each represents a point at coordinate (i, A[i]).
N vertical lines are drawn such that the two endpoints of line i is at (i, A[i]) and (i, 0).
Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
Problem Constraints
0 <= N <= 105
1 <= A[i] <= 105
Input Format
Single Argument representing a 1-D array A.
Output Format
Return single Integer denoting the maximum area you can obtain.
Example Input
Input 1:
A = [1, 5, 4, 3]
Input 2:
A = [1]
Example Output
Output 1:
6
Output 2:
0
Example Explanation
Explanation 1:
5 and 3 are distance 2 apart. So size of the base = 2. Height of container = min(5, 3) = 3.
So total area = 3 * 2 = 6
Explanation 2:
No container is formed.
*/
/*
Solution Approach
Description of approach 1:
Note 1: When you consider a1 and aN, then the area is (N-1) * min(a1, aN).
Note 2: The base (N-1) is the maximum possible.
This implies that if there was a better solution possible, it will definitely have height greater than min(a1, aN).
B * H > (N-1) * min(a1, aN)
We know that, B < (N-1)
So, H > min(a1, aN)
This means that we can discard min(a1, aN) from our set and look to solve this problem again from the start.
If a1 < aN, then the problem reduces to solving the same thing for a2, aN.
Else, it reduces to solving the same thing for a1, aN-1
*/
public class Solution {
public int maxArea(int[] A) {
int i=0, j=A.length-1, max = 0;
while(i<j){
int min = Integer.min(A[i], A[j]);
max = Integer.max(max, (j-i)*min);
// if(max==9336375){
// System.out.println(i+","+j+","+min);
// }
if(A[i]==min){
i++;
}
else{
j--;
}
}
return max;
}
}