盛水问题

方法一

暴力求解

 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
package main

import (
	"fmt"
)

func main() {
    numbers := []int{1,7,3,2,4,5,8,2,7};

    result := maxArea(numbers)
    fmt.Println(result)
}

func maxArea( height []int ) int {
    // write code here
    if(len(height) < 2) {
        return 0
    }
    maxCount,h := 0,0
    for i,h1 := range height {
        for j,h2 := range height {
            if(i>=j) {
                continue
            }
            h = h1
            if h1 > h2 {
                h = h2
            }
            if h * (j - i) > maxCount {
                maxCount = h * (j - i)
            }
        }
    }
    return maxCount;
}

方法二

双指针,夹逼

 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
package main

import (
	"fmt"
)

func main() {
    numbers := []int{1,7,3,2,4,5,8,2,7};

    result := maxArea(numbers)
    fmt.Println(result)
}

func maxArea( height []int ) int {
    // write code here
    if(len(height) < 2) {
        return 0
    }
    l, r, h := 0,len(height) - 1, 0
    maxCount := 0
    for l < r {
        h = height[l]
        if height[l] > height[r] {
            h = height[r]
        }
        if (r - l) * h > maxCount {
            maxCount = (r - l) * h
        }
        if height[l] > height[r] {
            r--
        } else {
            l++
        }
    }
    return maxCount;
}