Skip to content

Commit 86936bc

Browse files
committed
Time: 9413 ms (45.41%), Space: 19 MB (31.4%) - LeetHub
1 parent f08f55a commit 86936bc

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# time complexity: O(n * b ^ 2)
2+
# space complexity: O(n * b)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def maxProfit(
8+
self,
9+
n: int,
10+
present: List[int],
11+
future: List[int],
12+
hierarchy: List[List[int]],
13+
budget: int,
14+
) -> int:
15+
g = [[] for _ in range(n)]
16+
for e in hierarchy:
17+
g[e[0] - 1].append(e[1] - 1)
18+
19+
def dfs(u: int):
20+
cost = present[u]
21+
dCost = present[u] // 2
22+
23+
dp0 = [0] * (budget + 1)
24+
dp1 = [0] * (budget + 1)
25+
26+
subProfit0 = [0] * (budget + 1)
27+
subProfit1 = [0] * (budget + 1)
28+
uSize = cost
29+
30+
for v in g[u]:
31+
child_dp0, child_dp1, vSize = dfs(v)
32+
uSize += vSize
33+
for i in range(budget, -1, -1):
34+
for sub in range(min(vSize, i) + 1):
35+
if i - sub >= 0:
36+
subProfit0[i] = max(
37+
subProfit0[i],
38+
subProfit0[i - sub] + child_dp0[sub],
39+
)
40+
subProfit1[i] = max(
41+
subProfit1[i],
42+
subProfit1[i - sub] + child_dp1[sub],
43+
)
44+
45+
for i in range(budget + 1):
46+
dp0[i] = subProfit0[i]
47+
dp1[i] = subProfit0[i]
48+
if i >= dCost:
49+
dp1[i] = max(
50+
subProfit0[i], subProfit1[i - dCost] +
51+
future[u] - dCost
52+
)
53+
if i >= cost:
54+
dp0[i] = max(
55+
subProfit0[i], subProfit1[i - cost] + future[u] - cost
56+
)
57+
58+
return dp0, dp1, uSize
59+
60+
return dfs(0)[0][budget]
61+
62+
63+
n = 2
64+
present = [1, 2]
65+
future = [4, 3]
66+
hierarchy = [[1, 2]]
67+
budget = 3
68+
print(Solution().maxProfit(n, present, future, hierarchy, budget))
69+
n = 2
70+
present = [3, 4]
71+
future = [5, 8]
72+
hierarchy = [[1, 2]]
73+
budget = 4
74+
print(Solution().maxProfit(n, present, future, hierarchy, budget))
75+
n = 3
76+
present = [4, 6, 8]
77+
future = [7, 9, 11]
78+
hierarchy = [[1, 2], [1, 3]]
79+
budget = 10
80+
print(Solution().maxProfit(n, present, future, hierarchy, budget))
81+
n = 3
82+
present = [5, 2, 3]
83+
future = [8, 5, 6]
84+
hierarchy = [[1, 2], [2, 3]]
85+
budget = 7

0 commit comments

Comments
 (0)