Skip to content

Commit df68b8a

Browse files
authored
Create 1505-minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits.js
1 parent d03165d commit df68b8a

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* @param {string} num
3+
* @param {number} k
4+
* @return {string}
5+
*/
6+
const minInteger = function (num, k) {
7+
const nums = num.split("")
8+
const map = {}
9+
nums.forEach((n, i) => {
10+
map[n] = map[n] || []
11+
map[n].push(i)
12+
})
13+
14+
const used = new Set()
15+
const tree = new Fenwick(nums.length)
16+
let idx = 0
17+
let re = ""
18+
while (k > 0 && idx < nums.length) {
19+
for (let i = 0; i < 10; i++) {
20+
if (!map[i] || !map[i].length) continue
21+
const id = map[i][0]
22+
const cost = id - tree.query(id)
23+
if (k < cost) continue
24+
re += nums[id]
25+
k -= cost
26+
used.add(id)
27+
tree.update(id + 1, 1)
28+
map[i].shift()
29+
break
30+
}
31+
idx++
32+
}
33+
34+
for (let i = 0; i < nums.length; i++) {
35+
if (!used.has(i)) {
36+
re += nums[i]
37+
}
38+
}
39+
40+
return re
41+
}
42+
class Fenwick {
43+
constructor(n) {
44+
this.sums = new Array(n + 1).fill(0)
45+
}
46+
47+
update(i, delta) {
48+
while (i < this.sums.length) {
49+
this.sums[i] += delta
50+
i += i & -i
51+
}
52+
}
53+
54+
query(i) {
55+
let sum = 0
56+
while (i > 0) {
57+
sum += this.sums[i]
58+
i -= i & -i
59+
}
60+
return sum
61+
}
62+
}

0 commit comments

Comments
 (0)