Skip to content

Commit a351131

Browse files
authored
Create 2516-take-k-of-each-character-from-left-and-right.js
1 parent 2d22a26 commit a351131

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {string} s
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
const takeCharacters = function(s, k) {
7+
const cnt = {a: 0, b: 0, c: 0}
8+
const n = s.length
9+
for(const ch of s) {
10+
cnt[ch]++
11+
}
12+
if(cnt.a < k || cnt.b < k || cnt.c < k) return -1
13+
const limits = { a: cnt.a - k, b: cnt.b - k, c: cnt.c - k }
14+
let l = 0, r = 0, res = 0
15+
const hash = {a: 0, b: 0, c: 0}
16+
for(; r < n; r++) {
17+
const cur = s[r]
18+
hash[cur]++
19+
while(hash[cur] > limits[cur]) {
20+
hash[s[l]]--
21+
l++
22+
}
23+
24+
res = Math.max(res, r - l + 1)
25+
}
26+
27+
return n - res
28+
};

0 commit comments

Comments
 (0)