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