-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainerWithMostWater.kt
More file actions
39 lines (32 loc) · 1.03 KB
/
ContainerWithMostWater.kt
File metadata and controls
39 lines (32 loc) · 1.03 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
package leetcode
/**
* Problem description on [LeetCode](https://leetcode.com/problems/container-with-most-water/)
*/
class ContainerWithMostWater {
private fun area(height: IntArray, left: Int, right: Int): Int {
return minOf(height[left], height[right]) * (right - left)
}
fun maxArea(height: IntArray): Int {
var left = 0
var right = height.size - 1
var bestLeft = left
var bestRight = right
var bestArea = area(height, bestLeft, bestRight)
while (left < right) {
if (height[left] < height[right]) {
left++
} else {
right--
}
if (height[bestLeft] <= height[left] && height[bestRight] <= height[right]) {
val currArea = area(height, left, right)
if (bestArea < currArea) {
bestArea = currArea
bestLeft = left
bestRight = right
}
}
}
return bestArea
}
}