@@ -28,3 +28,91 @@ const maxTwoEvents = function(events) {
28
28
return dp [ idx ] [ cnt ]
29
29
}
30
30
} ;
31
+
32
+ // another
33
+
34
+ /**
35
+ * @param {number[][] } events
36
+ * @return {number }
37
+ */
38
+ const maxTwoEvents = function ( events ) {
39
+ const n = events . length , { max } = Math
40
+ let res = 0 , maxVal = 0 ;
41
+ const pq = new PriorityQueue ( ( a , b ) => a [ 0 ] < b [ 0 ] ) ;
42
+ events . sort ( ( a , b ) => a [ 0 ] === b [ 0 ] ? a [ 1 ] - b [ 1 ] : a [ 0 ] - b [ 0 ] )
43
+ for ( let e of events ) {
44
+ for ( ; ! pq . isEmpty ( ) && pq . peek ( ) [ 0 ] < e [ 0 ] ; pq . pop ( ) )
45
+ maxVal = max ( maxVal , pq . peek ( ) [ 1 ] ) ;
46
+ res = max ( res , maxVal + e [ 2 ] ) ;
47
+ pq . push ( [ e [ 1 ] , e [ 2 ] ] ) ;
48
+ }
49
+ return res ;
50
+ } ;
51
+
52
+ class PriorityQueue {
53
+ constructor ( comparator = ( a , b ) => a > b ) {
54
+ this . heap = [ ]
55
+ this . top = 0
56
+ this . comparator = comparator
57
+ }
58
+ size ( ) {
59
+ return this . heap . length
60
+ }
61
+ isEmpty ( ) {
62
+ return this . size ( ) === 0
63
+ }
64
+ peek ( ) {
65
+ return this . heap [ this . top ]
66
+ }
67
+ push ( ...values ) {
68
+ values . forEach ( ( value ) => {
69
+ this . heap . push ( value )
70
+ this . siftUp ( )
71
+ } )
72
+ return this . size ( )
73
+ }
74
+ pop ( ) {
75
+ const poppedValue = this . peek ( )
76
+ const bottom = this . size ( ) - 1
77
+ if ( bottom > this . top ) {
78
+ this . swap ( this . top , bottom )
79
+ }
80
+ this . heap . pop ( )
81
+ this . siftDown ( )
82
+ return poppedValue
83
+ }
84
+ replace ( value ) {
85
+ const replacedValue = this . peek ( )
86
+ this . heap [ this . top ] = value
87
+ this . siftDown ( )
88
+ return replacedValue
89
+ }
90
+
91
+ parent = ( i ) => ( ( i + 1 ) >>> 1 ) - 1
92
+ left = ( i ) => ( i << 1 ) + 1
93
+ right = ( i ) => ( i + 1 ) << 1
94
+ greater = ( i , j ) => this . comparator ( this . heap [ i ] , this . heap [ j ] )
95
+ swap = ( i , j ) => ( [ this . heap [ i ] , this . heap [ j ] ] = [ this . heap [ j ] , this . heap [ i ] ] )
96
+ siftUp = ( ) => {
97
+ let node = this . size ( ) - 1
98
+ while ( node > this . top && this . greater ( node , this . parent ( node ) ) ) {
99
+ this . swap ( node , this . parent ( node ) )
100
+ node = this . parent ( node )
101
+ }
102
+ }
103
+ siftDown = ( ) => {
104
+ let node = this . top
105
+ while (
106
+ ( this . left ( node ) < this . size ( ) && this . greater ( this . left ( node ) , node ) ) ||
107
+ ( this . right ( node ) < this . size ( ) && this . greater ( this . right ( node ) , node ) )
108
+ ) {
109
+ let maxChild =
110
+ this . right ( node ) < this . size ( ) &&
111
+ this . greater ( this . right ( node ) , this . left ( node ) )
112
+ ? this . right ( node )
113
+ : this . left ( node )
114
+ this . swap ( node , maxChild )
115
+ node = maxChild
116
+ }
117
+ }
118
+ }
0 commit comments