Written interview question: the container with the most water

     Originally published in:

 

     This weekend, look at an interview question from G company:

     Find the value of max{|ij|*min{a[i], a[j]}}, where a is an array of positive integers, and the interval between i and j is [0, n-1].

 

      This is actually the "container with the most water" in Leetcode, as follows:

 

       Lu Xun said: Violence can solve all problems.

       Hu Shi said: The problem that violence can solve is not a problem.

 

       Because the possibilities of i and j are limited combinations, brute force algorithms can get results, but they cannot pass the interview.

       Use dynamic programming? It seems that dynamic programming is not good.

       We can use double pointers to point to the head and tail respectively to calculate the water holding value. Then search the middle to try to find a greater possibility of holding water.     

       The barrel theory tells us: For two definite water holding baffles, the amount of water is determined by the short board.

       Therefore, when searching to the middle, moving the pointer from the side of the short board to the middle can produce a larger water holding value.

       This is a core conclusion.

 

       As for the code, it's very simple, let's take a look:

func maxArea(a []int) int {
    n := len(a)

    if n < 2 {
        return 0
    }

    if n == 2 {
        return min(a[1], a[0])
    }

    max := min(a[n - 1], a[0]) * (n - 1)

    i := 0
    j := n - 1

    for i < j  {
        if a[i] < a[j] {
            i++
        }else {
            j--
        }

        area := min(a[i], a[j]) * (j - i)
        if area > max {
            max = area
        }
    }

    return max
}

func min(x, y int) int {
    if x < y {
        return x
    }

    return y
}

      result:

 

      The algorithm can pass the interview normally. I wish you all your favorite offers.

 

      happy weekend.

Guess you like

Origin blog.csdn.net/stpeace/article/details/109544318