Skip to content

Commit 4cfe255

Browse files
authored
Update 2516-take-k-of-each-character-from-left-and-right.js
1 parent ae9cbce commit 4cfe255

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

2516-take-k-of-each-character-from-left-and-right.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,45 @@
1+
/**
2+
* @param {string} s
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
const takeCharacters = function(s, k) {
7+
const n = s.length
8+
const cnt = Array(3).fill(0)
9+
const a = 'a'.charCodeAt(0)
10+
for(const ch of s) {
11+
cnt[ch.charCodeAt(0) - a]++
12+
}
13+
const target = Array(3).fill(0)
14+
for(let i = 0; i < 3; i++) {
15+
target[i] = cnt[i] - k
16+
}
17+
for(let e of target) {
18+
if(e < 0) return -1
19+
}
20+
const arr = Array(3).fill(0)
21+
let res = 0
22+
let i = 0
23+
for(let j = 0; j < n; j++) {
24+
const idx = s[j].charCodeAt(0) - a
25+
arr[idx]++
26+
while(!valid()) {
27+
const ii = s[i].charCodeAt(0) - a
28+
arr[ii]--
29+
i++
30+
}
31+
res = Math.max(res, j - i + 1)
32+
}
33+
34+
return n - res
35+
36+
function valid() {
37+
return arr.every((e, i) => e <= target[i])
38+
}
39+
};
40+
41+
// another
42+
143
/**
244
* @param {string} s
345
* @param {number} k

0 commit comments

Comments
 (0)