Skip to content

Commit d8bcd6c

Browse files
committed
Runtime: 111 ms (Top 16.6%) | Memory: 50.12 MB (Top 33.3%)
1 parent 3e0bb8f commit d8bcd6c

File tree

1 file changed

+46
-13
lines changed

1 file changed

+46
-13
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,50 @@
1-
var makeLargestSpecial = function(s) {
2-
return recurse(s);
3-
4-
function recurse(s) {
5-
let i = 0, res = [], bal = 0;
6-
for (let j = 0; j < s.length; j++) {
7-
if (s[j] === '1') bal++;
8-
else bal--;
9-
if (bal === 0) { // found a balanced special substring
10-
res.push('1' + recurse(s.slice(i + 1, j)) + '0'); // s[i] must be 1 and s[j] must be 0, if 1...1, it would be invalid.
11-
i = j + 1; // go to next start position
1+
// Runtime: 111 ms (Top 16.6%) | Memory: 50.12 MB (Top 33.3%)
2+
3+
/**
4+
* @param {string} S
5+
* @return {string}
6+
*/
7+
var makeLargestSpecial = function (S) {
8+
let t = S
9+
while (true) {
10+
let t1 = largest(t)
11+
if (t1 == t) return t
12+
t = t1
13+
}
14+
function largest(S) {
15+
let arr = S.split('').map(x => Number.parseInt(x)),
16+
num = Number.parseInt(S, 2), rtn = S
17+
for (let firstEndIndex = 1; firstEndIndex < S.length - 2; firstEndIndex++) {
18+
for (let lLength = 2; lLength < firstEndIndex + 2; lLength += 2) {
19+
let firstStartIndex = firstEndIndex - lLength + 1
20+
if (!isSpecial(firstStartIndex, firstEndIndex)) continue
21+
for (let rLength = 2; rLength < S.length - firstEndIndex; rLength += 2) {
22+
let secondStartIndex = firstEndIndex + 1, secondEndIndex = firstEndIndex + rLength
23+
if (!isSpecial(secondStartIndex, secondEndIndex)) continue
24+
let str = [...arr.slice(0, firstStartIndex),
25+
...arr.slice(secondStartIndex, secondEndIndex + 1),
26+
...arr.slice(firstStartIndex, firstEndIndex + 1),
27+
...arr.slice(secondEndIndex + 1)].join('')
28+
let newNum = Number.parseInt(str, 2)
29+
if (newNum > num) {
30+
num = newNum
31+
rtn = str
32+
}
33+
}
34+
}
35+
}
36+
return rtn
37+
38+
function isSpecial(start, end) {
39+
let t = 0
40+
for (let i = start; i <= end; i++) {
41+
t += arr[i] == 1 ? 1 : -1
42+
if (t < 0) return false // this is the second rule, really bad description
1243
}
44+
return t == 0 ? true : false
1345
}
14-
res.sort((a, b) => b.localeCompare(a)); // sort substrings in desc order
15-
return res.join("");
1646
}
47+
1748
};
49+
50+
// console.log(makeLargestSpecial("101101011000"))

0 commit comments

Comments
 (0)