|
| 1 | +/** |
| 2 | + * [11] Container With Most Water |
| 3 | + * |
| 4 | + * Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. |
| 5 | + * |
| 6 | + * Note: You may not slant the container and n is at least 2. |
| 7 | + * |
| 8 | + * |
| 9 | + * |
| 10 | + * <img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg" style="width: 600px; height: 287px;" /> |
| 11 | + * |
| 12 | + * <small>The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </small> |
| 13 | + * |
| 14 | + * |
| 15 | + * |
| 16 | + * Example: |
| 17 | + * |
| 18 | + * |
| 19 | + * Input: [1,8,6,2,5,4,8,3,7] |
| 20 | + * Output: 49 |
| 21 | + * |
| 22 | + */ |
| 23 | +pub struct Solution {} |
| 24 | + |
| 25 | +// submission codes start here |
| 26 | + |
| 27 | +// Brute force: O(N^2) |
| 28 | + |
| 29 | +// Two Pointer: a[0] -> <- a[n-1] |
| 30 | +impl Solution { |
| 31 | + pub fn max_area(height: Vec<i32>) -> i32 { |
| 32 | + let (mut start, mut end) = (0_usize, (height.len() - 1)); |
| 33 | + let mut max: i32 = (end - start) as i32 * Solution::min(height[start], height[end]); |
| 34 | + let mut curr_area: i32 = 0; |
| 35 | + while end - start > 1 { |
| 36 | + // move the lower one |
| 37 | + if height[start] < height[end] { |
| 38 | + start += 1; |
| 39 | + if height[start] < height[start - 1] { continue } |
| 40 | + } else { |
| 41 | + end -= 1; |
| 42 | + if height[end] < height[end + 1] { continue } |
| 43 | + } |
| 44 | + curr_area = (end - start) as i32 * Solution::min(height[start], height[end]); |
| 45 | + if curr_area > max { max = curr_area } |
| 46 | + } |
| 47 | + max |
| 48 | + } |
| 49 | + |
| 50 | + #[inline(always)] |
| 51 | + fn min(i: i32, j: i32) -> i32 { |
| 52 | + if i > j { j } else { i } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// submission codes end |
| 57 | + |
| 58 | +#[cfg(test)] |
| 59 | +mod tests { |
| 60 | + use super::*; |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn test_11() { |
| 64 | + assert_eq!(Solution::max_area(vec![1, 8, 6, 2, 5, 4, 8, 3, 7]), 49); |
| 65 | + assert_eq!(Solution::max_area(vec![6, 9]), 6); |
| 66 | + assert_eq!(Solution::max_area(vec![1, 1, 2, 1, 1, 1]), 5); |
| 67 | + } |
| 68 | +} |
0 commit comments