File tree Expand file tree Collapse file tree 1 file changed +33
-25
lines changed Expand file tree Collapse file tree 1 file changed +33
-25
lines changed Original file line number Diff line number Diff line change 33 * @return {number }
44 */
55const largestVariance = function ( s ) {
6- const se = new Set ( s ) ,
7- n = s . length
8- let res = 0
9- for ( const x of se ) {
10- // max
11- for ( const y of se ) {
12- // min
13- if ( x != y ) {
14- let pre = Array ( n + 1 ) . fill ( 0 ) ,
15- preX ,
16- preY ,
17- diff = 0
18- for ( let i = 0 ; i < n ; i ++ ) {
19- if ( s [ i ] == x ) {
20- preX = i + 1
21- diff ++
22- }
23- if ( s [ i ] == y ) {
24- preY = i + 1
25- diff --
26- }
27- pre [ i + 1 ] = Math . min ( pre [ i ] , diff )
28- if ( preX == undefined || preY == undefined ) continue
29- res = Math . max ( res , diff - pre [ Math . min ( preX , preY ) - 1 ] )
6+ const freq = new Array ( 26 ) . fill ( 0 )
7+ const ac = 'a' . charCodeAt ( 0 )
8+ for ( let i = 0 ; i < s . length ; i ++ ) freq [ s . charCodeAt ( i ) - ac ] ++
9+
10+ // console.log(freq)
11+ let maxVariance = 0
12+ for ( let a = 0 ; a < 26 ; a ++ ) {
13+ for ( let b = 0 ; b < 26 ; b ++ ) {
14+ let remainingA = freq [ a ]
15+ let remainingB = freq [ b ]
16+ if ( a == b || remainingA == 0 || remainingB == 0 ) continue
17+
18+ // run kadanes on each possible character pairs (A & B)
19+ let currBFreq = 0 ,
20+ currAFreq = 0
21+ for ( let i = 0 ; i < s . length ; i ++ ) {
22+ let c = s . charCodeAt ( i ) - ac
23+
24+ if ( c == b ) currBFreq ++
25+ if ( c == a ) {
26+ currAFreq ++
27+ remainingA --
28+ }
29+ if ( currAFreq > 0 ) {
30+ maxVariance = Math . max ( maxVariance , currBFreq - currAFreq )
31+ }
32+
33+
34+ if ( currBFreq < currAFreq && remainingA >= 1 ) {
35+ currBFreq = 0
36+ currAFreq = 0
3037 }
3138 }
3239 }
3340 }
34- return res
41+
42+ return maxVariance
3543}
You can’t perform that action at this time.
0 commit comments