File tree Expand file tree Collapse file tree 2 files changed +27
-0
lines changed
minimum-adjacent-swaps-for-k-consecutive-ones Expand file tree Collapse file tree 2 files changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -45,6 +45,8 @@ Step 2. Add the dependency
45
45
46
46
<summary >展开查看</summary >
47
47
48
+ https://leetcode.cn/problems/minimum-adjacent-swaps-for-k-consecutive-ones
49
+
48
50
https://leetcode.cn/problems/form-array-by-concatenating-subarrays-of-another-array/
49
51
50
52
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/
Original file line number Diff line number Diff line change
1
+ function minMoves ( nums : number [ ] , k : number ) : number {
2
+ const g : number [ ] = [ ] ;
3
+ const preSum : number [ ] = [ ] ;
4
+ preSum . push ( 0 ) ;
5
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
6
+ if ( nums [ i ] === 1 ) {
7
+ g . push ( i - g . length ) ;
8
+ preSum . push ( preSum [ preSum . length - 1 ] + g [ g . length - 1 ] ) ;
9
+ }
10
+ }
11
+ const m = g . length ;
12
+ let res = Number . MAX_VALUE ;
13
+ for ( let i = 0 ; i <= m - k ; i ++ ) {
14
+ const mid = i + Math . floor ( k / 2 ) ;
15
+ const r = g [ mid ] ;
16
+ res = Math . min (
17
+ res ,
18
+ ( 1 - ( k % 2 ) ) * r +
19
+ ( preSum [ i + k ] - preSum [ mid + 1 ] ) -
20
+ ( preSum [ mid ] - preSum [ i ] ) ,
21
+ ) ;
22
+ }
23
+ return res ;
24
+ }
25
+ export default minMoves ;
You can’t perform that action at this time.
0 commit comments