Java - Maximum sum in path through a 2D array

前端 未结 3 1044
谎友^
谎友^ 2020-12-08 06:05

Basically I have a problem that goes something similar to this:

There is a garden of strawberry plants represented by a 2D, square array. Each plant(each element) h

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 06:17

    You can solve this with DP tabulation method, with which you can save space from O(m*n) to just O(n). With DP Memorization, you need m*n matrix to store intermediate values. Following is my Python code. Hope it can help.

    def max_path(field):
        dp = [sum(field[0][:i]) for i in range(1, len(field[0]) + 1)]
        for i in range(1, len(field)):
            for j in range(len(dp)):
                dp[j] = min(dp[j], dp[j - 1] if j > 0 else float('inf')) + field[i][j]
        return dp[-1]
    

提交回复
热议问题