File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
most-profitable-path-in-a-tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change @@ -127,6 +127,8 @@ https://leetcode.cn/problems/design-movie-rental-system/
127
127
128
128
https://leetcode.cn/problems/XxZZjK/
129
129
130
+ https://leetcode.cn/problems/most-profitable-path-in-a-tree
131
+
130
132
https://leetcode.cn/problems/magical-string/
131
133
132
134
https://leetcode.cn/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/
Original file line number Diff line number Diff line change
1
+ export default function mostProfitablePath (
2
+ edges : number [ ] [ ] ,
3
+ bob : number ,
4
+ amount : number [ ] ,
5
+ ) : number {
6
+ const g : number [ ] [ ] = amount . map ( ( ) => [ ] ) ;
7
+
8
+ for ( const [ x , y ] of edges ) {
9
+ g [ x ] . push ( y ) ;
10
+ g [ y ] . push ( x ) ;
11
+ }
12
+ const bobTime = amount . map ( ( ) => Infinity ) ;
13
+ function dfsBob ( x : number , fa : number , t : number ) : boolean {
14
+ if ( x === 0 ) {
15
+ bobTime [ x ] = t ;
16
+ return true ;
17
+ }
18
+ let found0 = false ;
19
+
20
+ for ( const y of g [ x ] ) {
21
+ if ( y != fa && dfsBob ( y , x , t + 1 ) ) {
22
+ found0 = true ;
23
+ }
24
+ }
25
+ if ( found0 ) {
26
+ bobTime [ x ] = t ; // 只有可以到达 0 才标记访问时间
27
+ }
28
+ return found0 ;
29
+ }
30
+ dfsBob ( bob , - 1 , 0 ) ;
31
+ g [ 0 ] . push ( - 1 ) ;
32
+ let ans = - Infinity ;
33
+
34
+ function dfsAlice ( x : number , fa : number , aliceTime : number , sum : number ) {
35
+ if ( aliceTime < bobTime [ x ] ) {
36
+ sum += amount [ x ] ;
37
+ } else if ( aliceTime == bobTime [ x ] ) {
38
+ sum += amount [ x ] / 2 ;
39
+ }
40
+ if ( g [ x ] . length == 1 ) {
41
+ // 叶子
42
+ ans = Math . max ( ans , sum ) ; // 更新答案
43
+ return ;
44
+ }
45
+ for ( const y of g [ x ] ) {
46
+ if ( y != fa ) {
47
+ dfsAlice ( y , x , aliceTime + 1 , sum ) ;
48
+ }
49
+ }
50
+ }
51
+ dfsAlice ( 0 , - 1 , 0 , 0 ) ;
52
+ return ans ;
53
+ }
You can’t perform that action at this time.
0 commit comments