算法图解案例

image.png

image.png

代码求解

  1. import numpy as np
  2. commodities = np.array([[1500, 3000, 2000], [1, 4, 3]]) # 商品列表,第一行表示商品的价格,第二行表示商品的重量
  3. arr = np.zeros((commodities.shape[1], 4), dtype=int) # 动态规划表格
  4. max_val = 0 # 能够偷取的商品的最大价值
  5. # 先填充表格的第一行(即偷取第一个商品)
  6. for j in range(0, arr.shape[1]):
  7. arr[0][j] = commodities[0][0] if commodities[1][0] <= j + 1 else 0
  8. # 依次偷取剩余商品然后比较价格
  9. for i in range(1, arr.shape[0]):
  10. for j in range(0, arr.shape[1]):
  11. if commodities[1][i] <= j + 1:
  12. left_space = j + 1 - commodities[1][i]
  13. before_val = arr[i - 1][j]
  14. current_val = commodities[0][i] if left_space == 0 else commodities[0][i] + arr[i - 1][left_space - 1]
  15. arr[i][j] = current_val if current_val > before_val else before_val
  16. else:
  17. arr[i][j] = arr[i - 1][j]
  18. max_val = arr.flatten()[-1] # 表格最后一个值为最后能够偷取的最大价值
  19. print(arr)
  20. print(max_val)