Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c486cad

Browse files
Create 3562-maximum-profit-from-trading-stocks-with-discounts.js
1 parent 214defd commit c486cad

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[]} present
4+
* @param {number[]} future
5+
* @param {number[][]} hierarchy
6+
* @param {number} budget
7+
* @return {number}
8+
*/
9+
var maxProfit = function (n, present, future, hierarchy, budget) {
10+
const freq = {}
11+
for (const [p, c] of hierarchy) {
12+
if (!freq[p]) freq[p] = []
13+
freq[p].push(c)
14+
}
15+
const MINI = -(10 ** 9)
16+
const ans = dfs(1, freq, budget, present, future, MINI)[0]
17+
return Math.max(...ans)
18+
19+
function dfs(u, freq, budget, present, future, MINI) {
20+
const dp = (freq[u] || []).map((child) =>
21+
dfs(child, freq, budget, present, future, MINI),
22+
)
23+
const a = Array(budget + 1).fill(MINI)
24+
const b = Array(budget + 1).fill(MINI)
25+
26+
for (let v = 0; v < 2; v++) {
27+
let x = Array(budget + 1).fill(MINI)
28+
let y = Array(budget + 1).fill(MINI)
29+
x[0] = 0
30+
const c = v === 0 ? present[u - 1] : Math.floor(present[u - 1] / 2)
31+
const profit = future[u - 1] - c
32+
if (c <= budget) {
33+
y[c] = profit
34+
}
35+
for (const [c0, c1] of dp) {
36+
const x1 = Array(budget + 1).fill(MINI)
37+
const y1 = Array(budget + 1).fill(MINI)
38+
for (let i = 0; i <= budget; i++) {
39+
if (x[i] > MINI) {
40+
for (let j = 0; j <= budget - i; j++) {
41+
if (c0[j] > MINI) {
42+
x1[i + j] = Math.max(x1[i + j], x[i] + c0[j])
43+
}
44+
}
45+
}
46+
}
47+
for (let i = 0; i <= budget; i++) {
48+
if (y[i] > MINI) {
49+
for (let j = 0; j <= budget - i; j++) {
50+
if (c1[j] > MINI) {
51+
y1[i + j] = Math.max(y1[i + j], y[i] + c1[j])
52+
}
53+
}
54+
}
55+
}
56+
x = x1
57+
y = y1
58+
}
59+
const dp1 = v === 0 ? a : b
60+
for (let i = 0; i <= budget; i++) {
61+
dp1[i] = Math.max(x[i], y[i])
62+
}
63+
}
64+
return [a, b]
65+
}
66+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /