File tree 1 file changed +11
-22
lines changed
1 file changed +11
-22
lines changed Original file line number Diff line number Diff line change 4
4
* @param {number } ladders
5
5
* @return {number }
6
6
*/
7
- const furthestBuilding = function ( heights , bricks , ladders ) {
8
- const queue = new PriorityQueue ( )
9
- for ( let i = 1 ; i < heights . length ; ++ i ) {
10
- if ( heights [ i ] > heights [ i - 1 ] ) {
11
- let diff = heights [ i ] - heights [ i - 1 ]
12
- if ( diff <= bricks ) {
13
- bricks -= diff
14
- queue . push ( diff )
15
- } else if ( ladders > 0 ) {
16
- let max = queue . isEmpty ( ) ? 0 : queue . pop ( )
17
- -- ladders
18
- if ( max > diff ) {
19
- bricks = bricks + max - diff
20
- queue . push ( diff )
21
- } else {
22
- queue . push ( max )
23
- }
24
- } else {
25
- return i - 1
26
- }
7
+ const furthestBuilding = function ( heights , bricks , ladders ) {
8
+ const pq = new PriorityQueue ( ( a , b ) => a < b )
9
+ const len = heights . length
10
+ for ( let i = 0 ; i < len - 1 ; i ++ ) {
11
+ const diff = heights [ i + 1 ] - heights [ i ]
12
+ if ( diff > 0 ) pq . push ( diff )
13
+ if ( pq . size ( ) > ladders ) {
14
+ bricks -= pq . pop ( )
27
15
}
16
+ if ( bricks < 0 ) return i
28
17
}
29
- return heights . length - 1
30
- }
18
+ return len - 1
19
+ } ;
31
20
class PriorityQueue {
32
21
constructor ( comparator = ( a , b ) => a > b ) {
33
22
this . heap = [ ]
You can’t perform that action at this time.
0 commit comments