最大水容量

       一道题目是这样的,假设一排连接在一起的高度不同的石头,石头的高度为整数;天降大雨,石头可以承载水;石头承载水的水量由两边的最大容量决定。那么,这么一排石头最大的承水量是多少。

       可以具体数学化为这样的情形:假设一个整形数组5,1,4;最大盛水量由5和4决定,最大高度为4,而最大盛水量为4-1=3。

       思路有了,即在数组找最大值,然后,再往两边找最最大值;然后,两边的最大值减去中间的数字大小,即为最大盛水量。

      直接上已经写好的代码:

 

# Arr = [4,3,2,2,3,4]
# Arr = [1,4,3,2,2,3,4,1]
# Arr = [2,1,3,1,4,3,2,2,3,4,1]
Arr = [2,1,3,1,4,3,2,2,3,4,1,5,]

def main():
    voluem_total = 0
    lpos_max, max_num = get_max_height_left(0, len(Arr))

    lpos, max_num_l = get_max_height_left(0, lpos_max)
    voluem_total += get_water_volume(lpos, lpos_max, max_num_l)

    while lpos != 0:
        pos_max_left = lpos
        lpos, max_num_left = get_max_height_left(0, pos_max_left)
        voluem_total += get_water_volume(lpos, pos_max_left, max_num_left)

    rpos, max_num_r = get_max_height_right(lpos_max, len(Arr) - 1)
    voluem_total += get_water_volume_r(lpos_max, rpos, max_num_r)

    while rpos < len(Arr) - 1:
        pos_max_right = rpos
        rpos, max_num_right = get_max_height_right(pos_max_right, len(Arr)-1)
        voluem_total += get_water_volume_r(pos_max_right, rpos, max_num_right)

    print("VolumeTotal:\t", voluem_total)

def get_max_height_left(left_Pos, right_Pos):
    pos = left_Pos
    max_Num = Arr[left_Pos]

    pos_temp = left_Pos
    while pos_temp < right_Pos:
        if max_Num < Arr[pos_temp]:
            max_Num = Arr[pos_temp]
            pos = pos_temp
        pos_temp += 1

    return pos, max_Num


def get_max_height_right(left_Pos, right_Pos):
    pos = right_Pos
    max_Num = Arr[right_Pos]

    pos_temp = right_Pos
    while pos_temp > left_Pos:
        if max_Num < Arr[pos_temp]:
            max_Num = Arr[pos_temp]
            pos = pos_temp
        pos_temp -= 1

    return pos, max_Num

def get_water_volume(left_pos, right_pos, max_num):
    l_pos = left_pos
    volume = 0

    while l_pos < right_pos:
        volume += max_num - Arr[l_pos] if max_num - Arr[l_pos] >0 else 0
        l_pos += 1

    return volume

def get_water_volume_r(left_pos, right_pos, max_num):
    r_pos = right_pos
    volume  = 0

    while r_pos > left_pos:
        volume += max_num - Arr[r_pos] if max_num - Arr[r_pos] > 0 else 0
        r_pos -= 1

    return volume

if __name__ == "__main__":
    main()

      该代码已经上传个人github:https://github.com/diziqian/waterVolume/blob/master/findWaterHeight.py

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章