提问人:WolfgangBagdanow 提问时间:9/18/2023 最后编辑:WolfgangBagdanow 更新时间:9/21/2023 访问量:201
连续 N 天从 M 种不同的蔬菜种子中获得最大利润
maximize profit from m different vegetable seeds for n consecutive days
问:
我有一个维度矩阵 V,其中每个元素代表连续几天不同蔬菜种子的预测价格。此外,还有一个整数 .我需要通过交易蔬菜种子找到最大的利润,但有限制,即在出售任何品牌的种子后,我几天内不能购买任何种子。并且必须先卖掉库存中的种子,然后才能再买一个。如果我在当天出售种子,则不允许在白天之前购买任何种子。m × n
m
n
c (1 ≤ c ≤ n − 2)
c
i
i + c + 1
输入:
• 维度矩阵 V,其中每个元素代表当天种子的预测价格。m × n (1 ≤ m, n ≤ 1000)
V[i][j] (0 ≤ V[i][j] ≤ (10000))
i-th
j-th
• 一个整数,表示在出售种子后购买其他品牌种子之前的等待时间。c (1 ≤ c ≤ n − 2)
输出:
返回表示事务的元组序列,其中:(i, j, l)
• 是所选种子的索引。i (1 ≤ i ≤ m)
• 是我购买种子以在这笔交易中实现利润最大化的日子。j1 (1 ≤ j1 ≤ n)
• 是我出售种子以在这笔交易中实现利润最大化的日子。j2 (1 ≤ j2 ≤ n)
~~~~例~~~~
如果 和 5X7 矩阵为:c = 2
V
[[2,9,8,4,5,0,7],
[6,7,3,9,1,0,8],
[1,7,9,6,4,9,11],
[7,8,3,1,8,5,2],
[1,8,4,0,9,2,1]]
预期产出为:
[(3, 1, 3),(2, 6, 7)]
说明:
为了获得最大的利润,在第 1 天买入 3 号种子,在第 3 天卖出。在第 6 天买入 2 号种子,在第 7 天卖出,等待期为 2 天。
我的工作:
def find_max_profit(V, c):
m, n = len(V), len(V[0])
max_profit = 0
transactions = []
# Create a list to store the maximum price after c + 1 days for each day.
max_prices = [0] * n
for i in range(n - 1, -1, -1):
if i + c + 1 < n:
max_prices[i] = max(V[i][i + c + 1:], default=0)
# Iterate over the rows of the matrix, and for each row, find the maximum difference between the price on the current day and the maximum price after c + 1 days.
for i in range(m):
buy_day, sell_day = 0, 0
max_diff = 0
for j in range(n):
if j > sell_day + c:
if V[i][j] - max_prices[j] > max_diff:
max_diff = V[i][j] - max_prices[j]
sell_day = j
if V[i][j] < V[i][buy_day]:
buy_day = j
if max_diff > 0:
transactions.append((i + 1, buy_day + 1, sell_day + 1))
max_profit += max_diff
return sorted(transactions)
V = [[2,9,8,4,5,0,7],
[6,7,3,9,1,0,8],
[1,7,9,6,4,9,11],
[7,8,3,1,8,5,2],
[1,8,4,0,9,2,1]]
c = 2
output = find_max_profit(V, c)
print(output)
我得到 的输出。所需的输出是 。[(1, 6, 7), (2, 6, 7), (3, 1, 7), (4, 4, 5), (5, 4, 5)]
[(3, 1, 3),(2, 6, 7)]
c = 2
我正在按照以下步骤获得最大利润:
从给定的输入矩阵 V 和整数开始。
c
对于每天,确定几天后(即当天或更晚)出售当天购买的种子的最高价格。
j
c + 1
j + c + 1
j
确定通过在当天购买的第 l 天出售种子来产生最大潜在利润的顺序。
(i,j,l)
ith
jth
答:
这是我目前的想法,我还没有时间实现和测试:动态程序的每个单元格可以有两种概念状态:买入或卖出。
如果是买入:
dp[row]["buy"][col] =
-price + (
max(dp[any_row]["sell"][col'])
where col' < col - c
or 0 if none
)
我们可以保持最好的查找。max(dp[any_row]["sell"][col'])
col - c - 1
如果是卖出:
dp[row]["sell"][col] =
price + max(dp[row]["buy"][col'])
where col' < col
or 0 if none
我们可以为每一行保持最佳状态。max(dp[row]["buy"][col']
col - 1
由于我们总是查看以前的列,因此我们可以逐列处理矩阵。
结果应为:
max(dp[any_row]["sell"][col])
where col ≤ last column
or 0 if none
后者我们可以边走边保存。
评论
c
i + c + 1